/* * A good sorting routine for large arrays. * Not a stable sort. */ int qsort(int *a, 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) { int x = a[low]; int i = low - 1; int j = high + 1; while(1) { while(a[--j] > x); while(a[++i] < x); if(i < j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } 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 a[10]; int main(int argc, char **argv) { int i; a[0] = 7; a[1] = 5; a[2] = 2; a[3] = 12; a[4] = 4; a[5] = 5; a[6] = 0; a[7] = 10; a[8] = 1; a[9] = 11; qsort(a, 10); for(i = 0; i != 10; i++) { print_string("a["); print_int(i); print_string("]="); print_int(a[i]); print_string("\n"); } return 0; }