# Thread: qsort with multi-dimensional arrays

1. ## qsort with multi-dimensional arrays

Hi,

I need some help with the syntax on this. If I have an array
d[1000][4] - how do I specify that I want the qsort funtion to sort on the 4th column?

I am currently running this code with a bubbe sort, but I thought it would run faster with qsort.

Thanks.

Diane

2. Do you want to sort the 4th column only or sort the rows based off the value of the 4th column?

3. The real trick is mastering how to write the compare function
Code:
```#include <stdio.h>
#include <stdlib.h>
#define MAX 10
void print ( int a[][4] ) {
int r,c;
for ( r = 0 ; r < MAX ; r++ ) {
for ( c = 0 ; c < 4 ; c++ ) {
printf( "%d ", a[r][c] );
}
printf( "\n" );
}
}

int cmp ( const void *pa, const void *pb ) {
const int (*a)[4] = pa;
const int (*b)[4] = pb;
if ( (*a)[3] < (*b)[3] ) return -1;
if ( (*a)[3] > (*b)[3] ) return +1;
return 0;
}

int main ( ) {
int a[MAX][4];
int r,c;
for ( r = 0 ; r < MAX ; r++ ) {
for ( c = 0 ; c < 4 ; c++ ) {
a[r][c] = rand() % 100;
}
}
qsort( a, MAX, sizeof a[0], cmp );
print( a );
return 0;
}```

4. Originally Posted by Thantos
Do you want to sort the 4th column only or sort the rows based off the value of the 4th column?
I want to sort the all of the array - based on the 4th column.

Thanks.

Diane

5. use the follwing program
#include"stdio.h"
#define c 1000
#define l 4
void main()

{
for(i=0;i<c;i++)
{for(j=0;j<l;j++)
{
printf("t[%d][%d]="i,j);
scanf("%d",&t[i][j]);
}
for(i=0;i<c;i++)
{for(j=0;j<l;j++)
{....
you want to sort the row or the colums

6. I want to sort the all of the array - based on the 4th column.

7. Thanks Salem!