// This program uses code from "Algorithms in C, Third Edition," // by Robert Sedgewick, Addison-Wesley, 1998. #include #include typedef int Item; #define key(A) (A) #define less(A, B) (key(A) < key(B)) #define exch(A, B) { Item t = A; A = B; B = t; } #define compexch(A, B) if (less(B, A)) exch(A, B) int partition(Item a[], int l, int r) { int i = l-1, j = r; Item v = a[r]; for (;;) { while (less(a[++i], v)) ; while (less(v, a[--j])) if (j == l) break; if (i >= j) break; exch(a[i], a[j]); } exch(a[i], a[r]); return i; } void quicksort_helper(Item a[], int l, int r) { int i; if (r <= l) return; i = partition(a, l, r); quicksort_helper(a, l, i-1); quicksort_helper(a, i+1, r); } void quicksort(Item a[], int length) { quicksort_helper(a, 0, length-1); } void print_array(int * a, int length) { int counter; for (counter = 0; counter < length; counter++) { printf ("%2d: %d\n", counter, a[counter]); } printf("\n"); } int main() { // int a[] = {17, 90, 70, 30, 60, 40, 45, 80, 10, 35}; int a[] = {10, 17, 30, 35, 60, 40, 45, 80, 90, 70}; print_array(a, 10); partition(a, 4, 9); // partition(a, 2, 6); // quicksort(a, 10); print_array(a, 10); return 0; }