Sort a two-dimensional array in C based on only the first column

I have a double type array with 2 columns and the maximum number of rows is 1000, which I want to sort based on the first element of each row, and then move the entire row. In essence, I want the second column element to have no effect.

I present the array as:

double A [1000] [2];

at my core. An example A may be:

18.0 2.0

5.5 3.5

10.0 8.1

4.0 2.5

After sorting, I would like it to look like this:

4.0 2.5

5.5 3.5

10.0 8.1

18.0 2.0

It would be nice to know how to sort it in reverse order so that it looks like this:

18.0 2.0

10.0 8.1

5.5 3.5

4.0 2.5

Note that it is sorted only by the value in the first column, then the entire row is switched.

, , , :

error: 'double []' sort_double_array (double A [] [], int n) {

? , . , , .

, .

,

.

+4
4

sort_double_array(double A[][2], int n);

, .

+3

void sort_double_array(double *A[], int n). size_t, int.

+1

, , , - ? 2D- . :

#define N 2

typedef struct
{
  double data [N];
} my_data_t;

:

my_data_t arr [1000];

" x". . ( ), qsort() stdlib.h.

qsort , . - :

int less (const void* a, const void* b)
{
  const my_data_t* ptr_a = a;
  const my_data_t* ptr_b = b;

   return (int)(a->data[0] - b->data[0]);
}

, "".

+1
#include<stdio.h>
#include<stdlib.h>
int main()
{
        int arr[4][2] = {18,2,5,3,10,8,4,2};
        int row=4,col=2;
        int i,j,k=0,x,temp;
        for(i=0;i<row;i++)
        {
                for(j=i+1;j<row;j++)
                {
                        if(arr[i][k] > arr[j][k])
                        {
                            for(x=0;x<2;x++) {
                                temp=arr[i][x];
                                arr[i][x]=arr[j][x];
                                arr[j][x]=temp;
                                }
                        }
                }
        }
        for(i=0;i<row;i++)
        {
                for(j=0;j<col;j++)
                printf("%d ", arr[i][j]);
                printf("\n");
        }
}
0

Source: https://habr.com/ru/post/1537636/


All Articles