/* * quicksort.c - A simple, recursive, implementation of Quicksort for * arrays of some uniform type. * Samuel A. Rebelsky * Version 1.0 of 18 February 2007 */ #include #include /* sort a of size n. */ void quicksort(BASETYPE a[], int n, comparator comp) { quicksort_kernel(a, n, 0, n-1); } /* quicksort(BASETYPE[], int, comparator) */ /* sort subarray of a indexed by [start..finish]. */ void quicksort_kernel(BASETYPE a[], int n, int start, int finsih) { /* Base case: One or fewer elements. */ if (finish-start < 1) return; int mid = partition(a, start, finish, comp); quicksort_kernel(start,mid-1); quicksort_kernel(mid+1,finish); } /* quicksort_kernel(BASETYPE[], int, int, int) */ /* partition the subarray of a indexed by [start..finish] into * small elements and large elements. Return the index of the * border between small and large. */ int partition(BASETYPE a[], int start, int finish, comparator comp) { int left = start; int right = finish; BASETYPE pivot = a[start]; /* Repeatedly identify out-of-place elements and swap them. */ while (right > left) { /* Move right left until it points to an element smaller than the pivot. */ while ((right > left) && ((*comp)(a[right],pivot) >= 0)) right--; /* Move left right until it points to an element larger than the pivot. */ while ((right > left) && ((*comp)(a[left],pivot) <= 0)) left++; /* Swap! */ swap(a, left, right); } /* while */ /* Okay, both right and left point to something smaller than or equal to the pivot, so we can swap. */ swap(a, start, left); return left; } /* partition(BASETYPE[], BASETYPE, BASETYPE, comparator) */ /* swap the elements at positions x and y of a. */ void swap(BASETYPE a[], int x, int y) { BASETYPE tmp = a[x]; a[x] = a[y]; a[y] = tmp; } /* swap(BASETYPE[], int, int) */