
Sorting Multi-Dim Array -- Help!
Quote:
> Help! How do you sort a multi-dimensional array? For example,
> if you had a 2 dimensional array, e.g., array [i][j], what would
> you do? I've tried to find some examples and can't. Is this
> possible?
> Diane Kresovich
> --
> Diane Kresovich
Diane...
The compare (... function for qsort (... would be the same for a
multi-dimensional array as for a single-dimensional array.
consider...
#include <stdio.h>
#include <stdlib.h>
/* 'compare (...'for 'qsort (...' */
int compare (const void *a, const void *b) {
/* return (*(int *)a > *(int *) b) - (*(int *)a < *(int *) b); */
if (*(int *) a > *(int *) b)
return 1;
if (*(int *) a < *(int *) b)
return -1;
return 0;
Quote:
}
int main (void) {
int array[10][10];
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
array[i][j] = rand () % 100;
printf ("%2d ", array[i][j]);
}
printf ("\n");
}
qsort (array, sizeof array / sizeof **array, sizeof **array, compare);
printf ("\n");
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++)
printf ("%2d ", array[i][j]);
printf ("\n");
}
return EXIT_SUCCESS;
Quote:
}
Regards
Brian