Quick sort
Partition around a pivot, then recursively sort the two sides.
Syllabus says: “Quick Sort”
On this page · 18 sections
PIVOT → PARTITION (smaller left, bigger right) → RECURSE on both sides. Bad pivot every time → O(n²).
A teacher picks one student's mark as the pivot and says ‘below this, go left; above this, go right’ — then repeats inside each group.
Quick sort chooses a pivot, partitions the array so that elements smaller than the pivot are on its left and larger ones on its right, and recursively sorts the two parts.
Learning objectives
- Partition an array around a pivot using both common schemes.
- Trace the recursion tree.
- Explain why the worst case is O(n²) and the average case O(n log n).
Prerequisites
Recursion, swapping, divide-and-conquer.
Introduction
Quick sort picks one element — the pivot — and rearranges the array so that everything smaller is on its left and everything larger on its right. The pivot is then in its final position, and the two sides are sorted independently.
Definition
Quick sort is a divide-and-conquer, in-place sorting algorithm: partition a[lo..hi] around a pivot p so that a[lo..p−1] ≤ a[p] ≤ a[p+1..hi], then recursively sort a[lo..p−1] and a[p+1..hi].
Two partition schemes you may be asked
1. First element as pivot (textbook / Horowitz)
i starts at lo and moves right until a[i] ≥ pivot; j starts at hi+1 and moves left until a[j] ≤ pivot. If i < j swap them and continue. When the pointers cross, swap the pivot a[lo] with a[j].
2. Last element as pivot (Lomuto / CLRS)
Keep a boundary i (initially lo−1). Scan j from lo to hi−1; whenever a[j] ≤ pivot, increment i and swap a[i] with a[j]. Finally swap a[i+1] with the pivot.
If the question does not say which pivot to use, state your choice in one line. Intermediate arrays depend on the scheme; the final sorted output does not.
Worked example
| Input | 26 5 37 1 61 11 59 15 48 19 |
|---|---|
| After partition 1 (pivot 26) | 11 5 19 1 15 26 59 61 48 37 |
| After partition 2 (pivot 11) | 1 5 11 19 15 26 59 61 48 37 |
| After partition 3 (pivot 1) | 1 5 11 19 15 26 59 61 48 37 |
| After partition 4 (pivot 19) | 1 5 11 15 19 26 59 61 48 37 |
| After partition 5 (pivot 59) | 1 5 11 15 19 26 48 37 59 61 |
| After partition 6 (pivot 48) | 1 5 11 15 19 26 37 48 59 61 |
Totals: comparisons = 29, swaps = 9, partitions = 6
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Also try: Quick sort, last element as pivot
Algorithm
- Step 1:Start.
- Step 2:Read the number of elements n and the n elements into the array A.
- Step 3:Call QuickSort(A, 0, n-1).
- Step 4:QuickSort(A, low, high): if low < high, go to Step 5; otherwise return.
- Step 5:Set pivot = A[low], i = low + 1 and j = high.
- Step 6:Repeat while i <= j:
- While i <= high and A[i] <= pivot, increment i.
- While A[j] > pivot, decrement j.
- If i < j, swap A[i] and A[j].
- Step 7:Swap A[low] and A[j]. The pivot is now in its final position j.
- Step 8:Call QuickSort(A, low, j-1).
- Step 9:Call QuickSort(A, j+1, high).
- Step 10:When the call in Step 3 is finished, display the sorted array A.
- Step 11:Stop.
Test i <= high before A[i] <= pivot. If every element is ≤ the pivot, i moves past the end, and testing A[i] first would read outside the array.
- Step 1:Start.
- Step 2:Read the number of elements n and the n elements into the array A.
- Step 3:Call QuickSort(A, 0, n-1).
- Step 4:QuickSort(A, low, high): if low < high, go to Step 5; otherwise return.
- Step 5:Call p = Partition(A, low, high).
- Step 6:Call QuickSort(A, low, p-1).
- Step 7:Call QuickSort(A, p+1, high).
- Step 8:Partition(A, low, high): set pivot = A[high] and i = low - 1.
- Step 9:Repeat for j = low to high-1:
- If A[j] <= pivot, increment i and swap A[i] and A[j].
- Step 10:Swap A[i+1] and A[high], and return i + 1 (the final position of the pivot).
- Step 11:When the call in Step 3 is finished, display the sorted array A.
- Step 12:Stop.
Pseudocode used by the animated lab · the lines highlighted in the visualizer
- 1QuickSort(a, lo, hi)
- 2if lo < hi
- 3pivot ← a[lo]; i ← lo; j ← hi + 1
- 4repeat i ← i + 1 until a[i] ≥ pivot
- 5repeat j ← j − 1 until a[j] ≤ pivot
- 6if i < j: swap a[i], a[j]
- 7repeat the scans until i ≥ j
- 8swap a[lo], a[j]
- 9QuickSort(a, lo, j − 1); QuickSort(a, j + 1, hi)
- 10end
- 1QuickSort(a, lo, hi)
- 2if lo < hi
- 3pivot ← a[hi]; i ← lo − 1
- 4for j ← lo to hi − 1: if a[j] ≤ pivot
- 5i ← i + 1; swap a[i], a[j]
- 6swap a[i + 1], a[hi]; p ← i + 1
- 7QuickSort(a, lo, p − 1); QuickSort(a, p + 1, hi)
- 8end
C implementation
quick_sort_first_pivot.ctested ✓ 228/228 cases/* Quick Sort, first element as pivot — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
void quickSort(int a[], int low, int high)
{
int pivot, i, j, temp;
if (low < high) {
pivot = a[low]; /* first element is the pivot */
i = low + 1;
j = high;
while (i <= j) {
while (i <= high && a[i] <= pivot) /* check i <= high first */
i++;
while (a[j] > pivot) /* stops at a[low] at worst */
j--;
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[low]; /* put the pivot in its place */
a[low] = a[j];
a[j] = temp;
quickSort(a, low, j - 1);
quickSort(a, j + 1, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
quickSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 10 Enter array elements: 45 36 12 65 24 11 44 54 17 33 Sorted array: 11 12 17 24 33 36 44 45 54 65
Bold = what you type. Everything else is printed by the program.
quick_sort_last_pivot.ctested ✓ 228/228 cases/* Quick Sort, last element as pivot (Lomuto partition) — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>
int partition(int a[], int low, int high)
{
int pivot, i, j, temp;
pivot = a[high]; /* last element is the pivot */
i = low - 1;
for (j = low; j < high; j++) {
if (a[j] <= pivot) {
i++;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i + 1]; /* put the pivot in its place */
a[i + 1] = a[high];
a[high] = temp;
return i + 1;
}
void quickSort(int a[], int low, int high)
{
int p;
if (low < high) {
p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
int main()
{
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
quickSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 10 Enter array elements: 45 36 12 65 24 11 44 54 17 33 Sorted array: 11 12 17 24 33 36 44 45 54 65
Bold = what you type. Everything else is printed by the program.
Complexity
| Case | When | Recurrence | Time |
|---|---|---|---|
| Best | pivot splits evenly | T(n) = 2T(n/2) + n | O(n log n) |
| Average | random input | — | O(n log n) |
| Worst | pivot is always min or max (e.g. sorted input with first-element pivot) | T(n) = T(n−1) + n | O(n²) |
Advantages and disadvantages
| Advantages | Disadvantages |
|---|---|
| Very fast in practice; in-place | Worst case O(n²) |
| Good cache behaviour | Not stable |
Edge cases
- Already sorted input with the first (or last) element as pivot → worst case. Fix: median-of-three or random pivot.
- All keys equal: Hoare-style scans still split evenly because both pointers stop on equal keys.
- Textbook code relies on a sentinel a[n] = +∞ so i cannot run off the end; our C version uses the check i ≤ right instead.
Common mistakes
- Swapping the pivot with a[i] instead of a[j] at the end of the first-element scheme.
- Forgetting that the pivot is excluded from both recursive calls.
- Writing O(n log n) as the worst case.
Asked in KTU exams (3)
- November 2025 · Q15a6 markssolved ✓Write algorithm to sort an array using quick sort. Apply quick-sort to sort the numbers 45,33,56,22,76,78,40 and 30.
- — 2024 · Q83 markssolved ✓Apply the Quick Sort algorithm (using the last element as the pivot) to sort the following list of numbers: [8,4,7,3,10]
- — 2024 · Q15b5 marksCreate a text file that contains the names and marks of students in a class. Then, read the data from the file, apply the Quick Sort algorithm to sort the students based on their marks in decreasing order, and store the sorted data back into a file.
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Partition → pivot final → recurse on both sides.
- Best/average O(n log n), worst O(n²); in-place, unstable.
- State the pivot rule you use.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing) §7.3 (Program 7.6)
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 Ch. 7
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)