Example 1 — First partition, then full sort
The pivot is the last element, 70.
#include <stdio.h>
static void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
static int partition(int a[], int lo, int hi) {
int pivot = a[hi], i = lo - 1;
for (int j = lo; j < hi; j++)
if (a[j] <= pivot) swap(&a[++i], &a[j]);
swap(&a[i + 1], &a[hi]);
return i + 1;
}
static void quick(int a[], int lo, int hi) {
if (lo < hi) {
int p = partition(a, lo, hi);
quick(a, lo, p - 1);
quick(a, p + 1, hi);
}
}
static void show(const char *label, const int a[], int n) {
printf("%s", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
int main(void) {
int b[] = {10, 80, 30, 90, 40, 50, 70};
int p = partition(b, 0, 6);
show("after first partition:", b, 7);
printf("pivot index: %d\n", p);
int a[] = {10, 80, 30, 90, 40, 50, 70};
quick(a, 0, 6);
show("sorted:", a, 7);
return 0;
} How It Works
- Values 10, 30, 40, and 50 are no larger than 70, so they move to the left side.
- The pivot 70 is swapped into index 4, its final position.
- Quick sort then recurses on the left four and the right two items.
