Quick sort, invented by C. A. R. Hoare around 1960, is the most widely used internal sorting method. It uses divide and conquer: one element, the pivot, is put in its final place, with smaller elements on its left and larger ones on its right, and the two sides are then sorted the same way.
Partitioning
Intuition
A teacher lines up students by height. She picks one student as a reference and asks everyone shorter to move to the left of that student and everyone taller to the right. The reference student is now exactly in the right spot; each side is then sorted the same way.
To sort A [ m . . n ] A[m..n] A [ m .. n ] with pivot k = A [ m ] k = A[m] k = A [ m ] :
Set i = m i = m i = m and j = n + 1 j = n + 1 j = n + 1 .
Move i i i right until A [ i ] ≥ k A[i] \ge k A [ i ] ≥ k (or i i i passes n n n ).
Move j j j left until A [ j ] ≤ k A[j] \le k A [ j ] ≤ k .
If i < j i < j i < j , swap A [ i ] A[i] A [ i ] and A [ j ] A[j] A [ j ] and go back to step 2; otherwise the scans have crossed.
Swap A [ m ] A[m] A [ m ] (the pivot) with A [ j ] A[j] A [ j ] . Now the pivot is at j j j , everything left of it is ≤ k \le k ≤ k and everything right of it is ≥ k \ge k ≥ k .
Sort A [ m . . j − 1 ] A[m..j-1] A [ m .. j − 1 ] and A [ j + 1.. n ] A[j+1..n] A [ j + 1.. n ] recursively.
Correction · Program 9.3: the left scan can run past the array
Study material says: Program 9.3 (§9.5.3) scans with do ++i; while (A[i] < k); without any bound on i; it uses an undeclared temp, the old-style declaration Quicksort(A,m,n) int A[],m,n, and an outer do … while (i<j) whose do is not shown.
Correct version: Stop the left scan at the end of the sub-array — while (i <= n && A[i] < k) — or place a sentinel larger than every key after the last element (Horowitz–Sahni’s version assumes A [ n + 1 ] = + ∞ A[n+1] = +\infty A [ n + 1 ] = + ∞ ). Declare temp (or use a swap function), use a prototype-style definition void quicksort(int A[], int m, int n), and write the loop structure completely, as in the program below.
Why: If the pivot A [ m ] A[m] A [ m ] is the largest key, every A [ i ] < k A[i] < k A [ i ] < k , so ++i runs past A [ n ] A[n] A [ n ] and reads (and may swap) memory outside the array — undefined behaviour. For example, sorting 5 1 2 starts with pivot 5 and no element stops the left scan. Old-style (K&R) definitions are obsolescent in C17 (§6.11.7) and removed in C23.
Example 9.8 Quick sort of 26 5 37 1 61 11 59 15 48 19
Goal. Sort the list, show the result of the first partition, and compare the work on random and on sorted input of 1000 elements.
Program.
C · quicksort.c Copy #include <stdio.h>
static long comparisons;
void swap( int * x, int * y) { int t = * x; * x = * y; * y = t; }
/* Quick sort of A[m..n] using A[m] as the dividing element (pivot).
The scans check their bounds, so no sentinel is needed. */
void quicksort( int A [] , int m, int n)
{
if (m >= n)
return ;
int k = A[m], i = m, j = n + 1 ;
while ( 1 ) {
do { i ++ ; comparisons ++ ; } while (i <= n && A[i] < k); /* from the left */
do { j -- ; comparisons ++ ; } while (A[j] > k); /* from the right */
if (i >= j)
break ; /* the scan pointers have crossed */
swap( & A[i], & A[j]);
}
swap( & A[m], & A[j]); /* pivot goes to its final place j */
quicksort(A, m, j - 1 );
quicksort(A, j + 1 , n);
}
void show( const int a [] , int n)
{
for ( int i = 0 ; i < n; i ++ ) printf( " %d" , a[i]);
printf( " \n " );
}
int main( void )
{
int a [] = { 26 , 5 , 37 , 1 , 61 , 11 , 59 , 15 , 48 , 19 };
printf( "input :" ); show(a, 10 );
quicksort(a, 0 , 9 );
printf( "sorted:" ); show(a, 10 );
/* first partition only, to see the pivot's final place */
int b [] = { 26 , 5 , 37 , 1 , 61 , 11 , 59 , 15 , 48 , 19 };
int k = b[ 0 ], i = 0 , j = 10 ;
while ( 1 ) {
do i ++ ; while (i <= 9 && b[i] < k);
do j -- ; while (b[j] > k);
if (i >= j) break ;
swap( & b[i], & b[j]);
}
swap( & b[ 0 ], & b[j]);
printf( "after the first partition (pivot 26 at index %d):" , j);
show(b, 10 );
/* comparisons for 1000 items: random order vs already sorted */
static int r[ 1000 ], s[ 1000 ];
unsigned seed = 12345 ;
for ( int x = 0 ; x < 1000 ; x ++ ) {
seed = seed * 1103515245 u + 12345 u ;
r[x] = ( int )((seed >> 8 ) % 100000 );
s[x] = x;
}
comparisons = 0 ; quicksort(r, 0 , 999 );
printf( "n = 1000, random input : %ld comparisons \n " , comparisons);
comparisons = 0 ; quicksort(s, 0 , 999 );
printf( "n = 1000, sorted input : %ld comparisons \n " , comparisons);
return 0 ;
}
Run it.
Output Copy input : 26 5 37 1 61 11 59 15 48 19
sorted: 1 5 11 15 19 26 37 48 59 61
after the first partition (pivot 26 at index 5): 11 5 19 1 15 26 59 61 48 37
n = 1000, random input : 11676 comparisons
n = 1000, sorted input : 501498 comparisons
Read the first partition. Pivot 26: the scans swap 37↔19 and 61↔15; then the pointers cross (i stops at 59, j at 11) and the pivot is swapped with 11 into index 5. Everything left of index 5 is smaller than 26, everything right is larger.
Result. The list is sorted; random input of 1000 elements took about 11,700 comparisons (≈ 1.2 n log 2 n \approx 1.2\, n \log_2 n ≈ 1.2 n log 2 n ), but already sorted input took about 500,000 (≈ n 2 / 2 \approx n^2/2 ≈ n 2 /2 ).
Running time
Case When Time Best / average Pivots split the array roughly in half O ( n log n ) O(n \log n) O ( n log n ) comparisonsWorst Pivot is always the smallest or largest (e.g. sorted input with first-element pivot) n ( n − 1 ) 2 = O ( n 2 ) \frac{n(n-1)}{2} = O(n^2) 2 n ( n − 1 ) = O ( n 2 ) Extra space Recursion stack O ( log n ) O(\log n) O ( log n ) on average, O ( n ) O(n) O ( n ) worst
Quick sort is not stable. Practical improvements: choose the pivot as the median of three (first, middle, last) or at random, which makes the worst case very unlikely; switch to insertion sort for small sub-arrays (about 10–20 elements); recurse on the smaller part first to keep the stack O ( log n ) O(\log n) O ( log n ) .
Key idea
Quick sort partitions around a pivot so that the pivot lands in its final place, then sorts both sides recursively; it averages O ( n log n ) O(n \log n) O ( n log n ) but degrades to O ( n 2 ) O(n^2) O ( n 2 ) when the pivots are badly chosen, such as the first element of sorted data.
TEE Exam note
“Sort the list using quick sort, showing each partition” is a very common question. Write the array after each partition with the pivot’s final place marked, and the recursive calls. State the average O ( n log n ) O(n \log n) O ( n log n ) and worst O ( n 2 ) O(n^2) O ( n 2 ) cases with the input that causes the worst case, and one improvement (median of three). Check Your Progress 3, Q2: quick sort uses divide and conquer .
Common mistake
Claiming quick sort is always O ( n log n ) O(n \log n) O ( n log n ) . With the first element as pivot, sorted or reverse-sorted input gives O ( n 2 ) O(n^2) O ( n 2 ) .
Common mistake
Forgetting the final swap that puts the pivot at position j j j . Without it the pivot stays at the front and the recursion is wrong.
Key takeaways
Divide and conquer: partition around a pivot, then sort both sides recursively.
Two scans move towards each other and swap out-of-place pairs; the pivot ends at j j j .
Bound the left scan (or use a sentinel) so it cannot leave the array.
Average O ( n log n ) O(n \log n) O ( n log n ) , worst O ( n 2 ) O(n^2) O ( n 2 ) ; not stable; median-of-three or random pivots help.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice Which programming technique does quick sort use?
A Divide and conquer B Greedy method C Dynamic programming D Backtracking
Check answer
Show answer Answer: A. Divide and conquer
It divides the array around a pivot and solves the two parts recursively (Check Your Progress 3, Q2).
Question 2 · multiple choice After one partition with pivot 40 on 40 20 70 10 50 30, which statement must be true?
A The whole array is sorted. B 40 is in its final sorted position, with 20, 10, 30 to its left in some order. C 40 is at index 0. D 70 is at the last index.
Check answer
Show answer Answer: B. 40 is in its final sorted position, with 20, 10, 30 to its left in some order.
Partitioning only guarantees the pivot’s position and the split; each side may still be unsorted.
Question 3 · multiple choice When does quick sort with the first element as pivot take O ( n 2 ) O(n^2) O ( n 2 ) time?
Check answer
Show answer Answer: C. When the input is already sorted (or reverse sorted)
Each partition then removes only the pivot, giving sub-arrays of sizes n − 1 , n − 2 , … n-1, n-2, \dots n − 1 , n − 2 , … : about n 2 / 2 n^2/2 n 2 /2 comparisons, as the program shows.
Question 4 · multiple choice What does this program print?
C · q9-partition.c Copy #include <stdio.h>
int main( void )
{
int A [] = { 30 , 50 , 10 , 70 , 20 };
int m = 0 , n = 4 , k = A[m], i = m, j = n + 1 , t;
while ( 1 ) {
do i ++ ; while (i <= n && A[i] < k);
do j -- ; while (A[j] > k);
if (i >= j) break ;
t = A[i]; A[i] = A[j]; A[j] = t;
}
t = A[m]; A[m] = A[j]; A[j] = t;
printf( "j=%d:" , j);
for ( int x = 0 ; x < 5 ; x ++ ) printf( " %d" , A[x]);
printf( " \n " );
return 0 ;
} A j=2: 10 20 30 50 70 B j=2: 10 20 30 70 50 C j=3: 20 10 50 30 70 D j=2: 20 10 30 70 50
Check answer
Show answer Answer: B. j=2: 10 20 30 70 50
i stops at 50, j at 20: swap → 30 20 10 70 50. Next i stops at 70 (index 3), j at 10 (index 2): crossed. Swapping the pivot with A[2] gives 10 20 30 70 50; the right side is not sorted yet.
Question 5 · multiple choice What is the average-case time of quick sort?
Check answer
Show answer Answer: D. O ( n log n ) O(n \log n) O ( n log n )
On average the pivots split the array reasonably evenly, giving O ( log n ) O(\log n) O ( log n ) levels of O ( n ) O(n) O ( n ) work.
Question 6 · short answer
Write a C function for quick sort using the first element as pivot, and state its best, average and worst-case complexity.
Show worked answer void quicksort(int A[], int m, int n) {
if (m >= n) return;
int k = A[m], i = m, j = n + 1, t;
while (1) {
do i++; while (i <= n && A[i] < k);
do j--; while (A[j] > k);
if (i >= j) break;
t = A[i]; A[i] = A[j]; A[j] = t;
}
t = A[m]; A[m] = A[j]; A[j] = t; /* pivot to its place */
quicksort(A, m, j - 1);
quicksort(A, j + 1, n);
}
Best and average case O ( n log n ) O(n \log n) O ( n log n ) ; worst case O ( n 2 ) O(n^2) O ( n 2 ) (e.g. sorted input with this pivot choice).