// Source: "Software Design ...", John A Robinson, Newnes, 2004, page 231. void quicksort(int *start, int *end); // Just the prototype int sort(int *array, const int num_in_array) // Wrapper for quicksort { quicksort(array, array + num_in_array - 1); return(0); } void quicksort(int *start, int *end) // The real thing { int *p, *q; int *centre; int pivot; if (end <= start) return; if (end == start + 1) { if (*end < *start) swap(end,start); return; } // At least three elements; do median of three to get pivot centre = start + (end-start)/2; if (*start > *centre) swap(start,centre); if (*start > *end) swap(start, end); if (*centre > *end) swap(centre, end); // Now with *centre as pivot, *start and *end are certainly // in the correct partitions. if (end == start + 2) return; // Get pivot value, then put pivot element out of the way pivot = *centre; swap(centre,end-1); p = start; q = end-1; // Now ready to partition the rest of the array while(1) { while(*++p < pivot); while(*--q > pivot); if (p >= q) break; swap(p,q); } // Finally put pivot element in its place swap(p,end-1); // And call recursively to do subarrays quicksort(start,p-1); quicksort(p+1,end); }