Quicksort
Choose a pivot and partition the sequence around it. Repeat on each smaller unsorted part.
Simple example
Choose 2 as the pivot. Move 1 to its left and 3 to its right. Each side now has one item.
Start3 1 2
Result1 2 3
using System;
int[] values = new int[] { 3, 1, 2 };
int pivot = values[2];
int boundary = 0;
int i = 0;
while (i < 2) {
if (values[i] < pivot) {
int saved = values[i];
values[i] = values[boundary];
values[boundary] = saved;
boundary += 1;
}
i += 1;
}
values[2] = values[boundary];
values[boundary] = pivot;
i = 0;
while (i < 3) {
Console.WriteLine(values[i]);
i += 1;
}
1 2 3
Advertisements
Everyday examples
Divide parcels by a sample weight
Weights are 8, 2 and 5 kilograms. Use 5 as the pivot. What goes on each side?
Start8 2 5
Result2 • 5 • 8
Two is lighter and eight is heavier. The pivot now separates the two groups.
Handle equal book prices
Every book costs 4. What would a three-way partition produce?
Start4 4 4
Result∅ • 4 4 4 • ∅
The equal group contains every book. Neither outer group needs more work.
Notice a poor pivot
Dates 1, 2, 3 and 4 are in order. Always choose the last date. What happens on the first split?
Start1 2 3 4
Result1 2 3 • 4 • ∅
One group still holds three items. Repeating this pattern wastes comparisons.
Cost and limits
Balanced partitions usually lead to O(n log n) work. Repeatedly choosing an extreme pivot can take O(n²).