Quick Sort: Partition, Recurse, and Count
Quick Sort sorts an array by placing one selected key in a valid final position, then sorting the ranges on either side. A key is the value used to order an item, such as a job priority or a timestamp. To trace Quick Sort accurately, you need the exact partition rule: different implementations can produce different intermediate arrays while still sorting correctly.
Partition around a pivot
A pivot is the selected key used to divide the active range. A partition rearranges that range so its keys satisfy a specified relationship to the pivot. Here, use the last-element method commonly called Lomuto partitioning, with a strict less-than test.
For inclusive indices lo through hi, save the last key as p and set a boundary index i = lo. Scan indices j from lo through hi - 1. Whenever A[j] < p, swap A[i] with A[j], then increase i. Otherwise, leave the boundary unchanged. After the scan, swap A[i] with A[hi] and return i as the pivot index q.
During the scan, positions before i contain keys less than the pivot. Scanned positions from i onward contain keys at least as large as it. Unscanned positions remain unclassified. The final swap therefore produces:
The slices in this display exclude their right endpoint. The inequalities apply to every key in each slice; they do not say that those keys are sorted.
Recurse on strictly smaller ranges
After partition returns q, sort the inclusive ranges lo through q - 1 and q + 1 through hi. These recursive calls apply the same procedure to smaller ranges. A range with zero or one key is already sorted, so return immediately when lo >= hi.
Exclude the placed pivot from both recursive ranges. Including it can repeat an unchanged range and prevent termination. Once both sides are sorted, the entire active range is sorted because every left key is smaller than the pivot and every right key is at least as large.
There is no separate step that combines the sorted sides. They already occupy their correct sides of the pivot in the array.
Understand running time and storage
One partition of n keys performs exactly n−1 comparisons between a scanned key and the pivot. If k keys go left, the other side contains n−k−1 keys. The total comparison count satisfies:
The table uses Θ notation to summarize how work grows with input size.
Partition pattern | Consequence | Comparison growth |
|---|---|---|
Roughly equal sides repeatedly | Many keys are processed at each of relatively few levels | Θ(nlogn) |
One empty side repeatedly | Active sizes decrease by only one key at a time | Θ(n2) |
Uniformly random pivots with distinct keys | Balanced splits are not guaranteed, but average work is controlled | Expected Θ(nlogn) |
Partitioning needs only a constant number of extra variables. However, the call stack also uses memory. With ordinary two-call recursion, its depth is Θ(logn) for balanced splits and Θ(n) in the worst case.
What to remember
- State the pivot-selection rule and the treatment of equal keys before tracing.
- Partition fixes one pivot; the side ranges may still be unsorted.
- Stop at ranges of size zero or one, and exclude the placed pivot from recursion.
- Split balance controls comparison growth and recursive storage.
Example: Sorting Delivery-Job Priorities
A dispatcher stores six distinct delivery-job priority scores in the array [42,17,63,28,51,36]. Smaller scores should appear first. Use indices starting at zero.
The pivot is the last key in each active range. Initialize the boundary i at the range's first index. Scan every earlier key; when a key is strictly less than the pivot, swap it with the boundary key and advance i. Finally, swap the pivot with the boundary key. Recursively sort the two sides, returning immediately for ranges containing zero or one key.
A key comparison is one test of a scanned key against its pivot. Exclude index tests and swaps from the comparison count.
a) Perform the first partition. Give the resulting array and the pivot's final index.
The first pivot is ________. Start with i = 0 and scan indices 0 through 4.
The key 42 fails the less-than test, so the array and boundary stay unchanged. The first accepted key is ________. Swap indices 0 and 1, then advance the boundary to 1:
The key 63 fails the test. The next accepted key is ________. Swap indices 1 and 3, then advance the boundary to 2:
The key 51 fails the test. Finally, swap indices 2 and 5 to place the pivot:
The resulting array is [17,28,36,42,51,63], and the pivot's final index is 2. Both left keys are below 36, and all three right keys are above it.
b) Complete the recursive partitions, processing the left side first. State the final sorted array.
The first recursive ranges are indices 0 through 1 and indices 3 through 5. The specified algorithm continues even though the current array happens to be sorted.
The left range is [17,28], with pivot ________. The key 17 passes the test. The swaps are with the same positions, so the range remains [17,28]. Its child ranges have sizes one and zero and return immediately.
The right range is [42,51,63], with pivot ________. Both scanned keys pass the test, and the range remains unchanged. Its left child is [42,51] and its right child is empty.
Partition [42,51] around 51. The key 42 passes the test, leaving the range unchanged. The remaining child ranges have sizes one and zero, so recursion ends.
The final sorted array is [17,28,36,42,51,63]. The partitioning ranges had sizes 6, 2, 3, and 2.
c) Find the total number of key comparisons in the complete sort.
The initial six-key partition compares the pivot with ________ other keys. The two-key left range contributes one comparison. The three-key right range contributes ________ comparisons, and its two-key child contributes one more.
Add only comparisons from ranges that require partitioning:
The complete sort uses 9 key comparisons. Calls on empty or singleton ranges contribute zero because they return before partitioning.
A scheduling system stores three records in the order 5A,5B,2C. Each number is a priority key; each subscript identifies a record. Sorting compares only the numbers.
Its Quick Sort implementation partitions each range as follows:
- Choose the last record as the pivot and set a boundary at the first position.
- Scan every record before the pivot from left to right. When its key is less than or equal to the pivot key, swap it with the boundary record and advance the boundary.
- Swap the pivot record with the boundary record, then recursively sort the ranges on either side. Ranges with fewer than two records are unchanged.
Trace the complete sort. Using the completed trace, classify this implementation of Quick Sort as stable or unstable: it is .
A scheduler stores priority scores in the array [39,14,31,8,26], indexed from 0 to 4. Perform exactly one Quick Sort partition using the last key as the pivot.
Set i = 0. Scan j = 0, 1, 2, 3; whenever A[j] < pivot, swap A[i] and A[j], then increase i. After scanning, swap A[i] with the last key. Do not perform recursive sorting.
Enter the final key at each index and the number of comparisons between scanned keys and the pivot. All entries are exact integers.
| Requested result | Value |
| Final key at index 0 | |
| Final key at index 1 | |
| Final key at index 2 | |
| Final key at index 3 | |
| Final key at index 4 | |
| Key comparisons |