Picture a classroom full of students standing in a messy line, and your job is to arrange them by height. You could compare every student with every other student, but that would take forever. Or you could be smarter: pick one student, call them the pivot, and ask everyone shorter to stand on the left and everyone taller to stand on the right. The pivot is now in exactly the right spot. Then you repeat the same trick on each side.
That, in a nutshell, is quick sort. It’s one of the most famous and widely used sorting algorithms out there, and once the pivot idea clicks, the rest falls into place. In this guide, we’ll walk through how the quick sort algorithm works, trace a full quick sort example by hand, write quick sort in Python, and break down its time complexity in plain English. We’ll also compare it with bubble sort, selection sort, insertion sort and merge sort.
What Is Quick Sort?
Quick sort is a divide and conquer sorting algorithm. Instead of sorting the whole list at once, it picks a pivot, partitions the list around it, and then sorts the two smaller pieces using the same method. Here are the three moves:
- Pick a pivot, one value from the list.
- Partition the list so smaller values sit on the left of the pivot and bigger values sit on the right.
- Repeat the process on the left part and the right part until every part has one value or none.
Quick sort was developed by the British computer scientist Tony Hoare in 1959 and published in 1961. It’s still used in some form in many real programming languages today.
The big difference from merge sort? Merge sort does the easy splitting first and the hard work (merging) afterwards. Quick sort does the hard work first (partitioning) and has nothing left to combine at the end, because once every pivot is in its final spot, the list is already sorted.
How Does Quick Sort Work? A Step-by-Step Example
Let’s sort the same list we used in our other sorting guides, in ascending order. To keep things simple, we’ll always use the last value as the pivot:
[29, 10, 14, 37, 13]
Watch Quick Sort in Action
Follow the pivot as it sorts the smaller values to its left and the bigger values to its right.
Pass 1: pivot = 13
- Scan from left to right and compare each value with the pivot.
29is bigger than13, so it stays.10is smaller, so it swaps places with29. The list is now [10, 29, 14, 37, 13].14and37are both bigger than13, so nothing moves.- Finally, swap the pivot with the first bigger value (
29).
The list becomes [10, 13, 14, 37, 29]. The value 13 is now locked into its final position. Everything on its left is smaller, and everything on its right is bigger.
Pass 2: sort the two sides
The left side is just [10]. One value is always sorted, so we're done there. The right side is [14, 37, 29], so we repeat the process with 29 as the pivot. 14 is smaller, so it stays on the left. 37 is bigger, so it stays on the right. Swapping the pivot with 37 gives [10, 13, 14, 29, 37].
What's left is [14] and [37], which are single values. Sorted! Notice that we never had to merge anything at the end. Each pivot landed in its final spot along the way.
Quick Sort in Python
Here's a beginner-friendly, in-place version of quick sort. It uses a common partition method called the Lomuto partition scheme, which is the same "last value as pivot" approach we traced above:
def quick_sort(arr, low=0, high=None):
if high is None:
high = len(arr) - 1
# Base case: 0 or 1 items means this part is already sorted
if low < high:
pivot_index = partition(arr, low, high)
quick_sort(arr, low, pivot_index - 1) # sort the left part
quick_sort(arr, pivot_index + 1, high) # sort the right part
return arr
def partition(arr, low, high):
pivot = arr[high] # use the last value as the pivot
i = low - 1 # end of the "smaller than pivot" group
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# Put the pivot right after the smaller group
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
numbers = [29, 10, 14, 37, 13]
print(quick_sort(numbers))
# Output: [10, 13, 14, 29, 37]A few details worth noticing:
partitiondoes the heavy lifting. It moves smaller values to the left, puts the pivot in its final spot, and returns that spot's index.imarks the end of the "smaller than pivot" group, andjscans through the list looking for values to add to it.- The
if low < highcheck is the base case. Without it, the recursion would never stop. - The list is sorted in place, so no extra list is created, unlike the usual merge sort.
Quick Sort Time and Space Complexity
Quick sort's speed depends heavily on how well the pivot splits the list.
| Case | Time complexity | Why? |
|---|---|---|
| Best | O(n log n) | Each pivot splits the list into two roughly equal halves. |
| Average | O(n log n) | On random data, splits are usually balanced enough. |
| Worst | O(n²) | Each pivot is the smallest or largest value, so one side is always empty. |
Why O(n log n) on average?
Every partition pass looks at each value in its section once, which is about n work per level. If the splits are reasonably balanced, the list only needs about log n levels of splitting before every piece is down to one value. Multiply them and you get O(n log n). The split doesn't even have to be perfect. Even a lopsided 90/10 split every time still gives roughly log n levels.
Space complexity
Quick sort sorts in place, so it doesn't need a second list. It does use the call stack for recursion, which takes about O(log n) space on average. In the worst case, that stack can grow to O(n).
The Worst Case (and How to Avoid It)
Here's the catch. With the simple "last value" pivot, an already sorted list is the worst possible input. Take [1, 2, 3, 4, 5]. The pivot is 5, the biggest value, so everything lands on the left and the right side is empty. The next pass has the same problem, and the one after that too. We end up doing (n - 1) + (n - 2) + ... + 1 = n(n - 1) / 2 comparisons, which is O(n²). Reverse-sorted lists cause the same trouble, and the version in this guide also slows down badly when a list is full of equal values.
Good implementations avoid this by choosing the pivot more carefully:
- Random pivot: pick a random value, so no particular input can reliably trigger the worst case.
- Median-of-three: take the median of the first, middle and last values.
- Switch to another method for small parts: many libraries use insertion sort once a section gets small.
A simple fix for our code is to swap a random value into the last position before partitioning. With that one tweak, the worst case becomes very unlikely on real data, even though it's still possible in theory.
Is Quick Sort Stable?
No. Quick sort is not stable, which means equal values can end up in a different order than they started. The long-distance swaps during partitioning are the reason. Here's a tiny example with two equal values labelled 3a and 3b:
[3a, 3b, 1] → [1, 3b, 3a]The pivot 1 gets swapped with the first value, which sends 3a all the way to the end, behind 3b. If you need equal items to keep their original order, use a stable sort such as merge sort or insertion sort instead.
Quick Sort vs. Merge Sort vs. Other Sorting Algorithms
| Algorithm | Best | Average | Worst | Extra space | Stable? |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick sort | O(n log n) | O(n log n) | O(n²) | O(log n) average | No |
So which is better, quick sort or merge sort? It depends on what you need:
- Quick sort is often faster in practice on arrays, partly because it sorts in place and works well with how computers cache memory. The downside is the
O(n²)worst case and no stability. - Merge sort guarantees
O(n log n), is stable, and suits linked lists and huge files. The downside is the extraO(n)memory.
Where Quick Sort Is Used in the Real World
You'll rarely write quick sort by hand in a real project, but its ideas are everywhere. C++'s std::sort is typically implemented as introsort, which starts as quick sort and switches to heap sort if the recursion gets too deep, so the worst case is avoided. Java sorts primitive arrays such as int[] with a tuned dual-pivot quick sort. Python is the odd one out: sorted() and list.sort() use Timsort, a mix of merge sort and insertion sort, because Python needs a stable sort.
Advantages and Disadvantages of Quick Sort
Advantages
- Very fast on average,
O(n log n). - Sorts in place with little extra memory.
- Works well on large arrays and plays nicely with computer caches.
- The pivot idea is simple once you see it.
Disadvantages
O(n²)worst case if the pivots are chosen badly.- Not stable.
- Recursion can go deep on unlucky inputs.
- A little trickier to get right than the simple sorts, especially with duplicates.
When Should You Use Quick Sort?
- Large arrays in memory where you want strong average speed and little extra space.
- When stability doesn't matter, for example sorting plain numbers.
- Learning and interviews. Quick sort questions come up constantly, usually about pivots, partitioning and the worst case.
Skip it when you need guaranteed worst-case performance, stable ordering, or you're sorting linked lists. In everyday code, your language's built-in sort is usually the best choice.
Common Mistakes to Avoid
- Forgetting the base case. Always check
low < highbefore partitioning, or the recursion never ends. - Including the pivot in a recursive call. After partitioning, the pivot is final. Recurse on
pivot_index - 1andpivot_index + 1, not on the pivot itself. - Forgetting the final pivot swap. Without it, the pivot never reaches its correct position.
- Always using the first or last value as the pivot. It's fine for learning, but it turns sorted input into a worst case.
- Assuming it's stable. It isn't, so don't rely on it to keep equal items in order.
Try It Yourself
- Modify the code to sort in descending order.
- Add a counter to see how many comparisons it makes on a random list versus an already sorted list.
- Add a random pivot by swapping a random value into
arr[high]before partitioning, then repeat the test. - Sort a list of tuples like
(name, grade)and watch equal grades change order.
Quick Recap
Quick sort picks a pivot, partitions the list so smaller values go left and bigger values go right, then repeats on each side. It's fast on average (O(n log n)), sorts in place, and powers the sorting functions in several major languages. The trade-offs are an O(n²) worst case with poor pivots and no stability. If you've followed this series, you now know the five classic sorts: bubble, selection, insertion, merge and quick sort.
Frequently Asked Questions
What is quick sort in simple words?
Quick sort picks one value as a pivot, moves smaller values to its left and bigger values to its right, and then repeats the same process on each side until everything is in order.
What is the time complexity of quick sort?
The best and average cases are O(n log n). The worst case is O(n²), which happens when the pivots keep splitting the list very unevenly.
Why is quick sort called "quick"?
Because on average it's very fast in practice, often faster than other O(n log n) algorithms on arrays.
Is quick sort better than merge sort?
Not always. Quick sort is often faster on arrays and uses less memory, but merge sort guarantees O(n log n) and is stable.
Is quick sort in-place?
Yes. It rearranges values inside the original list. It only uses a small amount of extra memory for the recursion stack.
How do you avoid the worst case in quick sort?
Choose the pivot more carefully, for example with a random pivot or median-of-three, so a sorted or reversed list doesn't cause lopsided splits.
Does Python use quick sort?
No. Python's built-in sorted() and list.sort() use Timsort, a hybrid of merge sort and insertion sort.
Found this helpful? Try running the Python code on lists of different sizes and orders, then compare it against merge sort and insertion sort. Counting comparisons side by side is the fastest way to see why pivot choice matters.
