Is there an easy way to sort a multi-dimensional array using qsort?
Printable View
Is there an easy way to sort a multi-dimensional array using qsort?
Depends what you call easy. The only really tricky bit to qsort is writing the comparision function.
The only downside to sorting multi dimensional arrays is the size of elements which qsort must swap. This example has to swap 20 bytes to exchange strings, where it would be more efficient if pointers were used.
Code:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_ENTRIES(c) (sizeof(c)/sizeof(c[0]))
/* you would really want to use char*'s here */
/* its much easier to swap a pointer than an array of 20 chars */
char test[][20] = {
"hello",
"world",
"how",
"are",
"you"
};
/* define a typedef for the minor array subscripts */
/* better than writing const char (*pa)[20] = a; */
typedef char foo[20];
int compare ( const void *a, const void *b ) {
const foo *pa = a;
const foo *pb = b;
return strcmp( *pa, *pb );
}
int main ( ) {
int i, num = NUM_ENTRIES(test);
printf( " Before\n" );
for ( i = 0 ; i < num ; i++ ) printf( "%s\n", test[i] );
qsort( test, num, sizeof(test[0]), compare );
printf( "\n After\n" );
for ( i = 0 ; i < num ; i++ ) printf( "%s\n", test[i] );
return 0;
}
MSVC++
Code:const foo *pa = (const char(*)[20])a;
const foo *pb = (const char(*)[20])b;
Well that is certainly better than the alternative--writing my own qsort.
I have another qsort solution somewheres...