int print_string(char *); int print_int(int); /* * Structure version. * This is meant more as a stress test, * rather than a usable algorithm. */ struct item { int index; char data[10]; }; /* * A good sorting routine for large arrays. * Not a stable sort. */ int qsort(struct item *a, int (*compare)(struct item, struct item), int len) { /* * Reorder the elements in a into two contiguous groups. If * ret is the return value, then the first group is the * elements in low..ret, and the second group is the elements * in ret+1..high. Each element in the second group will be at * least as large as every element in the first group. */ int partition(int low, int high) { struct item x = a[low]; int i = low - 1; int j = high + 1; while(1) { while(compare(a[--j], x) > 0); while(compare(a[++i], x) < 0); if(i < j) { struct item temp = a[i]; a[i] = a[j]; a[j] = temp; 0; } else return j; } } /* * Inner quicksort takes bounds. */ int quicksort(int low, int high) { if(!(low < high)) return 0; int mid = partition(low, high); quicksort(low, mid); quicksort(mid + 1, high); } /* * Call quick sort with the right bounds. */ return quicksort(0, len - 1); } /* * Test program. */ int main(int argc, char **argv) { struct item a[10]; int i; int compare(struct item a, struct item b) { a.index - b.index; } a[0].index = 7; a[1].index = 5; a[2].index = 2; a[3].index = 12; a[4].index = 4; a[5].index = 5; a[6].index = 0; a[7].index = 10; a[8].index = 1; a[9].index = 11; qsort(a, compare, 10); for(i = 0; i != 10; i++) { print_string("a["); print_int(i); print_string("].index="); print_int(a[i].index); print_string("\n"); } return 0; }