Watch quick sort take the last element as pivot and partition the array around it, step by step. Worked example, the sorted input trap and O(n log n) average.
About this algorithm
Quick sort picks one value as a pivot, moves everything smaller than it to its left and everything else to its right, drops the pivot between the two groups, where it is now in its final place, and then sorts each group the same way. It takes O(n log n) time on average but O(n²) when the pivots keep landing at one end, and it sorts in place. On typical data it is the fastest of the classic comparison sorts.
Quick sort is the default for sorting arrays in memory: it needs no extra array, its inner loop is short, and it reads memory in order, which caches handle well. Most standard libraries use a version of it, such as introsort in C++. Choose merge sort instead when you need a stable sort or a guaranteed n log n bound, and heap sort when you need that guarantee with no extra memory. On small or nearly sorted arrays insertion sort is quicker, and library quick sorts switch to it for short slices.
This page uses the Lomuto scheme: the pivot is the last value of the slice from low to high.
Keep a boundary i just before the slice. Walk j from low to high - 1. Whenever the value at j is smaller than the pivot, move i one step right and swap the values at i and j, so the small side grows by one.
Swap the pivot into slot i + 1. Everything to its left is smaller and everything to its right is not, so this slot is final.
Sort low to i, then i + 2 to high. A slice of zero or one value needs no work.
This page opens on 40 random bars, so type 7,2,9,4,1,5 into the Custom box to follow along. The pivot is 5. 7 is bigger and stays. 2 is smaller, so it swaps with 7: 2 7 9 4 1 5. 9 stays. 4 is smaller and swaps with 7: 2 4 9 7 1 5. 1 is smaller and swaps with 9: 2 4 1 7 9 5. The pivot swaps with 7 into index 3: 2 4 1 5 9 7, and 5 never moves again. The left slice 2 4 1 has pivot 1, which nothing beats, so 1 goes to the front; then 4 2 is partitioned around 2. The right slice 9 7 is partitioned around 7. The array ends as 1 2 4 5 7 9 after 9 comparisons.
With the last value as pivot, an array that is already sorted makes every pivot the largest value. Each partition peels off one value, the recursion goes n levels deep, and the work becomes n²/2 comparisons. Picking the pivot at random, or as the median of the first, middle and last values, makes that case very unlikely.
Time: each level of partitions looks at every value once, and balanced splits give about log n levels; a pivot that is always the smallest or largest gives n levels instead. Space: the partition works in place, so the only extra memory is the recursion stack, about log n deep on balanced splits and up to n deep in the worst case.