# Thread: sorting 2D arrays

1. ## sorting 2D arrays

Hi,
I have written a program that is meant to sort a small 2 dimensional array (ten groups of two numbers) in descending order, by the first number (column [0]).

It works when I use small numbers, such as 1 2, 4 10, 3 6, 9 15, 20 56, 2 1, 5 34, 18 29, 2 2, 31 1, but when I use a bit bigger number like 2 3, 65 12, 23 3, 6 98, 25 10, 65 3, 1 2, 2 1, 43 12, 63 23. it freezes.

What have I stuff up?? and then after that is fixed.

Code:
```#include <stdio.h>

#define ROWS 10
#define COLUMNS 2

int improve_order (int array[ROWS][COLUMNS], int len);

int main( int argc, char **argv) {

int array[ROWS][COLUMNS];
int i;

printf("Enter 10 pairs of integers:\n");

for( i=0; i<ROWS; i=i+1) {
scanf("%d %d", &array[i][0], &array[i][1]);
}

int a=1;
while(a==1) {
a=improve_order (array, ROWS);
}
printf("Sorted in desending order for first element and asending order for second element:\n");

for(i=0; i<ROWS; i=i+1) {
printf("%d %d\n", array[i][0], array[i][1]);
}
printf("\n");

return 0;

}

int improve_order (int array[ROWS][COLUMNS], int len) {
int swapped1=0;
int temp1,temp3;
int i=0;

while(i<ROWS-1) {
if( array[i][0] < array[i+1][0]) {
temp1=array[i][0];
array[i][0]=array[i+1][0];
array[i+1][0]=temp1;

temp1=array[i][1];
array[i][1]=array[i+1][1];
array[i+1][1]=temp1;
swapped1=1;
}

/*if ( array[i][1]> array[i+1][1]) {
temp2=array[i][1];
array[i][0]=array[i+1][1];
array[i+1][1]=temp2;
swapped1=1;
}*/

if ( (array[i][0]== array[i+1][0]) && (array[i][1]> array[i+1][1]) ) {
temp3= array[i][1];
array[i+1][i]=array[i][1];
array[i][1]=temp3;
swapped1=1;
}

i=i+1;
}

return swapped1;
}```

2. Think about what happens in 'improve_order' when i is 9.

3. So 11 will sort out as less than 2?

Popular pages Recent additions