Quick sort
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Quick sort picks one item as the pivot, moves smaller items to its left and larger ones to its right, then repeats on each side. It is usually the fastest general-purpose sort in memory, and its partition idea is also used to pick the top items quickly.
Practical use cases
- Web app: Sorting search results by price in the browser. A shopping page has loaded 2,000 products and the user clicks "Price: low to high". The built-in sort, which is often quick sort based, reorders them in a few milliseconds, so the list changes the instant the user clicks, without another server request.
- Web app: Finding the median salary. An HR dashboard needs the median pay from 1 lakh records without fully sorting them. A quick-sort style partition step finds the middle value by looking at only the part that matters. The report loads faster than if it sorted everything.
- System: Standard library sorts. Many standard libraries, such as C and C++ ones, use a quick-sort based method for general arrays because it is very quick on average and does its work inside the same array. That is why it appears behind so many everyday sort functions and database engines.
The story: The Captain Picks a Line
Aarav, captain of the mohalla cricket team, had to line up twenty kids for the team photo, shortest on the left, tallest on the right. Asking everyone to compare with everyone else would take forever.
So he picked one kid, Raju, as the pivot. "Everyone shorter than Raju, go to his left. Everyone taller, go to his right!" In one quick round, Raju was standing in exactly the spot he would be in the finished photo, even though the left and right groups were still jumbled.
Then Aarav did the same to the left group: pick a pivot, shorter ones left, taller ones right. And the same to the right group. The groups got smaller and smaller, each pivot locking into its place, until every group had at most one kid.
That is quick sort: choose a pivot, partition around it, and repeat on both sides. It is usually the fastest sort in practice, as long as the pivots split the groups reasonably evenly.
How to spot this problem, and where you need it
You need to sort a large list in memory as fast as possible, or you need only the k-th smallest item or the top few, without paying for a full sort.
Signs you need it
- The data is big but fits in memory, and you want the fastest typical sort with little extra space.
- The problem says "partition around a pivot", "k-th smallest", "median" or "Dutch national flag".
- You need the middle or top-k item and sorting everything feels wasteful.
Where to use it in a project
- Client-side sorting of product tables, user lists and reports in the browser or server memory.
- Finding medians, percentiles or the top few results without sorting the entire data.
The solution
Pick a pivot item, ideally a random or middle one. Walk through the list moving smaller items to one side and larger ones to the other, so the pivot lands in its final place. Then repeat the same steps on the left part and the right part. For the k-th smallest, continue only in the side that contains position k, and ignore the other side.
Payoff: Before: nested loops took seconds on 2,000 products. After: a few milliseconds, and the median is found without a full sort.
Explain it like I am 8
Pick one friend in the crowd. Tell shorter kids to stand on his left and taller kids on his right. Now he is in the right place for good! Do the same trick inside each smaller crowd until there are no crowds left.
How it works, step by step
- Pick a pivot from the range. This lesson uses the last item.
- Partition: walk through the range and move every item smaller than the pivot to the left side, keeping a marker
iwhere the next small item goes. - Place the pivot by swapping it into position
i. It is now in its final spot. - Recurse on the part left of the pivot and the part right of the pivot.
- A range of 0 or 1 items is already sorted, which is the base case that stops the recursion.
The code in four languages
PHP
<?php
// Quick sort (Lomuto partition, last item as pivot), sorts the array in place.
function quickSort(array &$a, int $lo, int $hi): void {
if ($lo >= $hi) return; // 0 or 1 items: already sorted
$pivot = $a[$hi];
$i = $lo; // next spot for a "shorter than pivot" item
for ($j = $lo; $j < $hi; $j++) {
if ($a[$j] < $pivot) {
[$a[$i], $a[$j]] = [$a[$j], $a[$i]];
$i++;
}
}
[$a[$i], $a[$hi]] = [$a[$hi], $a[$i]]; // drop the pivot into its final place
quickSort($a, $lo, $i - 1); // sort the shorter side
quickSort($a, $i + 1, $hi); // sort the taller side
}
$players = [6, 3, 8, 2, 7, 1, 5];
quickSort($players, 0, count($players) - 1);
echo implode(', ', $players); // 1, 2, 3, 5, 6, 7, 8JavaScript
// Quick sort (Lomuto partition, last item as pivot), sorts the array in place.
function quickSort(a, lo = 0, hi = a.length - 1) {
if (lo >= hi) return a; // 0 or 1 items: already sorted
const pivot = a[hi];
let i = lo; // next spot for a "shorter than pivot" item
for (let j = lo; j < hi; j++) {
if (a[j] < pivot) {
[a[i], a[j]] = [a[j], a[i]];
i++;
}
}
[a[i], a[hi]] = [a[hi], a[i]]; // drop the pivot into its final place
quickSort(a, lo, i - 1); // sort the shorter side
quickSort(a, i + 1, hi); // sort the taller side
return a;
}
console.log(quickSort([6, 3, 8, 2, 7, 1, 5]).join(', ')); // 1, 2, 3, 5, 6, 7, 8Java
import java.util.*;
public class Main {
// Quick sort (Lomuto partition, last item as pivot), sorts the array in place.
static void quickSort(int[] a, int lo, int hi) {
if (lo >= hi) return; // 0 or 1 items: already sorted
int pivot = a[hi];
int i = lo; // next spot for a "shorter than pivot" item
for (int j = lo; j < hi; j++) {
if (a[j] < pivot) {
int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
i++;
}
}
int tmp = a[i]; a[i] = a[hi]; a[hi] = tmp; // drop the pivot into its final place
quickSort(a, lo, i - 1); // sort the shorter side
quickSort(a, i + 1, hi); // sort the taller side
}
public static void main(String[] args) {
int[] players = {6, 3, 8, 2, 7, 1, 5};
quickSort(players, 0, players.length - 1);
System.out.println(Arrays.toString(players)); // [1, 2, 3, 5, 6, 7, 8]
}
}Go
package main
import "fmt"
// quickSort (Lomuto partition, last item as pivot) sorts the slice in place.
func quickSort(a []int, lo, hi int) {
if lo >= hi {
return // 0 or 1 items: already sorted
}
pivot := a[hi]
i := lo // next spot for a "shorter than pivot" item
for j := lo; j < hi; j++ {
if a[j] < pivot {
a[i], a[j] = a[j], a[i]
i++
}
}
a[i], a[hi] = a[hi], a[i] // drop the pivot into its final place
quickSort(a, lo, i-1) // sort the shorter side
quickSort(a, i+1, hi) // sort the taller side
}
func main() {
players := []int{6, 3, 8, 2, 7, 1, 5}
quickSort(players, 0, len(players)-1)
fmt.Println(players) // [1 2 3 5 6 7 8]
}Time: O(n log n) average, O(n²) worst · Extra space: O(log n). Good pivots halve the groups. A terrible pivot every time (like the smallest on a sorted list when you always pick the last) makes it slow. The space is the recursion stack.
Watch out for
- Always taking the last item as pivot on already sorted data. Every split is lopsided and it degrades to O(n²). Real code picks a random or middle pivot.
- Recursing with
iinstead ofi - 1andi + 1. The pivot is already final and must be left out. - Assuming it is stable. Swapping items far apart can reorder equal items.
Quick check
- After one partition, what is true about the pivot?
- It is in its final sorted position
- It is at the start of the list
- Both halves are sorted
- When is quick sort (last-item pivot) at its worst?
- A random list
- An already sorted list
- A list of 2 items
- What does quick sort recurse on after partitioning?
- Only the right side
- The whole list again
- The left and right sides, but not the pivot