quicksort(int left, int right) { int i; if (right > left) { i = partition(left, right); quicksort(left, i-1); quicksort(i+1, right); } } Figure 3. The Quicksort algorithm. [figure ends] [figure] /* QWIKSORT.C Simple implementation of Quicksort in C, sorts an array of numbers. Ray Duncan * PC Magazine May 1988 */ #include #include #define N_ITEMS 25 /* size of array */ static int items[N_ITEMS]; /* numbers to be sorted */ void quicksort(int, int); /* function prototype */ main(int argc, char *argv[]) { int i, j; /* some scratch variables */ char buffer[80]; /* some scratch space for keyboard input */ while(1) /* get numbers & sort them */ { puts("\nEnter numbers to be sorted..."); i = 0; /* initialize array index */ while(i < N_ITEMS) /* enforce maximum entries */ { printf("%2d: ", i+1); /* prompt user */ /* read the keyboard */ gets(buffer); /* last entry if empty line */ if(buffer[0] == 0 ) break; /* convert ASCII number to binary and save it */ items[i] = atoi(buffer); i++; /* bump array pointer */ } if(i==0) exit(0); /* if no numbers exit */ quicksort(0, i-1); /* sort the numbers */ puts("\nHere are the sorted numbers..."); j = 0; /* initialize array pointer */ while (j < i) /* display sorted numbers */ { printf("%2d: %d\n", j+1, items[j]); j++; /* bump array pointer */ } } } /* Quicksorts an array of integers, recursing to sort subsets of the array. Called with the index to the left and right members of the array to be sorted. */ void quicksort(int left, int right) { int i, j, t; /* some scratch variables */ if(right > left) /* skip unnecessary calls */ { i = left-1; j = right; /* initialize scan pointers */ /* partition array on value */ /* of the rightmost item */ do { /* scan right for item >= */ /* than partitioning value */ do i++; while(items[i] < items[right]); /* scan left for item <= */ /* than partitioning value */ do j--; while(items[j] > items[right] && j > 0); t = items[i]; /* interchange the items */ items[i] = items[j]; items[j] = t; } while(j > i); /* do until pointers cross */ items[j] = items[i]; /* undo the last swap and */ items[i] = items[right]; /* put the partitioning */ items[right] = t; /* element into position */ quicksort(left, i-1); /* sort items to left of */ /* partitioning element */ quicksort(i+1, right); /* sort items to right of */ } /* partitioning element */ }