Quick sort picks one value as the pivot and rearranges the array so that everything smaller than the pivot comes before it and everything else after it — a step called partitioning. The pivot is now in its final place, and the two sides are sorted the same way, recursively.
j, keeping a boundary i — everything before i is smaller than the pivot. When nums[j] is smaller, swap it to i and move i on. Finally swap the pivot into i.Each partition puts one pivot in its final place; then each side is partitioned the same way.
function quickSort(nums, lo = 0, hi = nums.length - 1) { if (lo >= hi) return nums; // 0 or 1 values: nothing to do const p = partition(nums, lo, hi); quickSort(nums, lo, p - 1); // sort the smaller values... quickSort(nums, p + 1, hi); // ...and the bigger ones return nums;} function partition(nums, lo, hi) { const pivot = nums[hi]; // Lomuto: the last value is the pivot let i = lo; // nums[lo..i) are smaller than the pivot for (let j = lo; j < hi; j++) { if (nums[j] < pivot) { [nums[i], nums[j]] = [nums[j], nums[i]]; i++; } } [nums[i], nums[hi]] = [nums[hi], nums[i]]; // the pivot lands in its final place return i;}Each level of partitioning looks at every value once. If pivots land near the middle, the ranges halve and there are about log n levels: O(n log n), which is the average for random input. If the pivot is always the smallest or largest value — for example taking the last value of an already sorted array — one side is empty every time, there are n levels, and it degrades to O(n²). The recursion uses O(log n) stack on average, O(n) in that worst case.
The usual fix is a random pivot: swap a random value of the range into nums[hi] before partitioning. Then no particular input is reliably bad, and O(n²) becomes vanishingly unlikely. Production versions also pick the median of three values and switch to insertion sort for tiny ranges.
It's the general-purpose in-memory sort: C++'s std::sort is introsort (quick sort that switches to heap sort if the recursion goes too deep), and Java sorts primitives with dual-pivot quick sort. Its partition step is a pattern on its own — Sort Colors, Sort Array By Parity and Kth Largest Element (quickselect) are all partitions.