Quick Sort is an in-place divide-and-conquer sorting algorithm. In practical benchmarks, Quick Sort is typically 2x to 3x faster than Merge Sort and Heap Sort due to excellent CPU hardware cache locality and minimal memory movement.
Imagine a gym teacher organizing 30 students by height:
arr[high].i maintains the boundary of elements smaller than the pivot.j scans from low to high - 1.arr[j] <= pivot, increment i and swap arr[i] with arr[j].low - 1 and high + 1) and advance inward toward each other.If you always choose the first or last element as the pivot:
Pick three candidates (first, middle, last), find their mathematical median, and swap it to the pivot position. This guarantees balanced $O(n \log n)$ partitions in production!
[10, 80, 30, 90, 40, 50, 70] (Pivot = 70)j | arr[j] | arr[j] <= 70? | i | Swap Action | Array State |
|---|---|---|---|---|---|
| Init | - | - | -1 | None | [10, 80, 30, 90, 40, 50, 70] |
| 0 | 10 | Yes | 0 | Swap arr[0] with arr[0] | [10, 80, 30, 90, 40, 50, 70] |
| 1 | 80 | No | 0 | None | [10, 80, 30, 90, 40, 50, 70] |
| 2 | 30 | Yes | 1 | Swap arr[1] (80) with arr[2] (30) | [10, 30, 80, 90, 40, 50, 70] |
| 3 | 90 | No | 1 | None | [10, 30, 80, 90, 40, 50, 70] |
| 4 | 40 | Yes | 2 | Swap arr[2] (80) with arr[4] (40) | [10, 30, 40, 90, 80, 50, 70] |
| 5 | 50 | Yes | 3 | Swap arr[3] (90) with arr[5] (50) | [10, 30, 40, 50, 80, 90, 70] |
| Final | - | - | - | Swap arr[4] (80) with pivot 70 | [10, 30, 40, 50, 70, 90, 80] |
Pivot 70 is placed at index 4! All items to its left are $< 70$, all to its right are $> 70$.
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.