/* quickSort.cc for use with sortMain.cc */ // code by david saunders (taken from Sedgewick, page 118). 2/96 typedef int itemType; // Must be a type on which the comparator > can be used. // these three defs are wanted by sortMain.cc #define quickSort sort char* id = "quick"; char* ate = "g(N) := N*log[2](N);"; // quickSort() uses partition() which uses swap(). inline void swap(itemType a[], int i, int j){ itemType v = a[i]; a[i] = a[j]; a[j] = v; } inline int partition(itemType a[], int lo, int hi){ /* Let v = a[hi]. partition() permutes the elements in the array so that all elements less than v are at the beginning of a and all the elements larger than v are at the end. The resulting index of v itself (between these two groups) is returned. */ itemType v = a[hi]; int i = lo - 1; int j = hi; for (;;) { while (v > a[++i]); // a[lo..i-1] are < v. while (a[--j] > v); // a[j+1..hi] are > v. if (i >= j) break; // partition almost done swap(a, i, j); } swap(a, i, hi); return i; } void quickSort(itemType a[], int lo, int hi){ // The items of a[lo..hi] are permuted into sorted order. // Side effect: a[0] is overwritten. if (lo < hi) { int mid = partition(a, lo, hi); quickSort(a, lo, mid - 1); quickSort(a, mid + 1, hi); } // else one or no elements -- and that's already sorted. }