Quick Sort in C++
1. What Is Quick Sort?
Quick Sort is a sorting algorithm that works by selecting one element as a pivot and partitioning the remaining elements around it.
After partitioning, the pivot reaches its final sorted position. The algorithm then applies the same process to the elements before and after the pivot.
Example
Consider the following array:
arr = {8, 3, 1, 7, 0, 10, 2}
After sorting using Quick Sort:
arr = {0, 1, 2, 3, 7, 8, 10}
2. Important Terms in Quick Sort
Pivot
The pivot is the element selected to divide the array into smaller and larger elements. Depending on the partition method, the pivot can be selected from the beginning, end, middle, or randomly.
Partition
Partitioning rearranges elements so that they are placed on the appropriate sides of the pivot according to the chosen partition rule.
Recursive Sorting
After partitioning, Quick Sort recursively sorts the portions on either side of the pivot.
3. How Does Quick Sort Work?
Consider this array:
arr = {6, 3, 8, 5, 2, 7}
For this example, choose the last element as the pivot.
Step 1: Select the Pivot
Pivot = 7
Step 2: Partition the Array
Rearrange the elements so that values smaller than or equal to 7 appear before the pivot and values greater than 7 appear after it.
{6, 3, 5, 2, 7, 8}
The pivot 7 is now in its final sorted position.
Step 3: Sort the Left Portion
{6, 3, 5, 2}
Apply Quick Sort to the left portion using another pivot.
Step 4: Sort the Right Portion
{8}
A single-element portion is already sorted.
Final Sorted Array: 2 3 5 6 7 8
4. Quick Sort Algorithm
Quick Sort commonly uses two functions:
- partition(): Places the pivot into its partition position and rearranges the other elements.
- quickSort(): Recursively sorts the portions before and after the pivot.
Pseudocode
quickSort(arr, low, high):
if low < high:
pivotIndex = partition(arr, low, high)
quickSort(arr, low, pivotIndex - 1)
quickSort(arr, pivotIndex + 1, high)
5. Understanding the Partition Function
The partition function is the most important part of Quick Sort. There are different partitioning methods, including Lomuto Partition and Hoare Partition.
In this lesson, we use the Lomuto Partition scheme, which selects the last element as the pivot.
Lomuto Partition Steps
- Select the last element as the pivot.
- Initialize a boundary index at low - 1.
- Traverse the array from low to high - 1.
- When an element is less than or equal to the pivot, increase the boundary index.
- Swap that element with the element at the boundary index.
- After traversal, place the pivot immediately after the boundary index.
- Return the pivot's final index.
Partition Pseudocode
partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j = low to high - 1:
if arr[j] <= pivot:
i = i + 1
swap arr[i] and arr[j]
swap arr[i + 1] and arr[high]
return i + 1
6. C++ Code: Quick Sort Using Lomuto Partition
The following program implements Quick Sort using the Lomuto Partition scheme.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int partition(vector<int>& arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(vector<int>& arr, int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
int main() {
vector<int> arr = {8, 3, 1, 7, 0, 10, 2};
int n = arr.size();
quickSort(arr, 0, n - 1);
cout << "Sorted Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Sorted Array: 0 1 2 3 7 8 10
7. Understanding the Quick Sort Code
Selecting the Pivot
int pivot = arr[high];
The last element of the current array portion is selected as the pivot.
Initializing the Boundary
int i = low - 1;
The variable i tracks the boundary of the portion containing elements smaller than or equal to the pivot.
Traversing the Array
for (int j = low; j < high; j++)
The variable j checks every element before the pivot.
Comparing with the Pivot
if (arr[j] <= pivot)
If the current element is smaller than or equal to the pivot, it belongs in the left partition.
Swapping Elements
i++;
swap(arr[i], arr[j]);
The boundary is moved forward and the current element is placed inside the left partition.
Placing the Pivot
swap(arr[i + 1], arr[high]);
The pivot is moved immediately after the left partition. This gives it its final sorted position.
Recursive Calls
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
These calls sort the portions before and after the pivot. The pivot itself is excluded because it is already in its correct position.
8. Dry Run of Quick Sort
Consider the following array:
arr = {4, 2, 6, 1, 3}
First Partition
The last element, 3, is selected as the pivot.
| Element Checked | Comparison | Action |
|---|---|---|
| 4 | 4 > 3 | No swap |
| 2 | 2 <= 3 | Move into left partition |
| 6 | 6 > 3 | No swap |
| 1 | 1 <= 3 | Move into left partition |
After placing the pivot:
{2, 1, 3, 4, 6}
The pivot 3 is now in its correct position.
Second Partition
Quick Sort now processes the left portion {2, 1}. Select 1 as the pivot.
{1, 2, 3, 4, 6}
The right portion {4, 6} is also processed recursively. It is already in sorted order after partitioning.
Final Sorted Array: 1 2 3 4 6
9. Quick Sort Using Hoare Partition
Hoare Partition is another popular partitioning method. Unlike Lomuto Partition, it generally uses two pointers that move toward each other from opposite ends of the array.
How Hoare Partition Works
- Select a pivot, commonly the first element.
- Move the left pointer forward until an element greater than or equal to the pivot is found.
- Move the right pointer backward until an element smaller than or equal to the pivot is found.
- If the pointers have not crossed, swap the two elements.
- Repeat until the pointers cross.
- Return the right pointer as the partition boundary.
C++ Code: Hoare Partition
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int hoarePartition(vector<int>& arr, int low, int high) {
int pivot = arr[low];
int i = low - 1;
int j = high + 1;
while (true) {
do {
i++;
} while (arr[i] < pivot);
do {
j--;
} while (arr[j] > pivot);
if (i >= j) {
return j;
}
swap(arr[i], arr[j]);
}
}
void quickSortHoare(vector<int>& arr, int low, int high) {
if (low < high) {
int p = hoarePartition(arr, low, high);
quickSortHoare(arr, low, p);
quickSortHoare(arr, p + 1, high);
}
}
int main() {
vector<int> arr = {8, 3, 1, 7, 0, 10, 2};
quickSortHoare(arr, 0, (int)arr.size() - 1);
cout << "Sorted Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Sorted Array: 0 1 2 3 7 8 10
10. Time Complexity of Quick Sort
Quick Sort's time complexity depends on how evenly the pivot divides the array.
Best Case
The best case occurs when the pivot divides the array into two nearly equal parts at each level.
Best Case = O(n log n)
Average Case
On average, partitions are sufficiently balanced, so the algorithm performs O(n log n) work.
Average Case = O(n log n)
Worst Case
The worst case occurs when the pivot repeatedly becomes the smallest or largest element. One partition then contains almost all the elements, while the other contains none.
This can happen, for example, when using the last element as the pivot on an already sorted array with distinct elements.
Worst Case = O(n²)
11. Space Complexity of Quick Sort
Quick Sort performs partitioning inside the original array, so the partition operation itself uses O(1) auxiliary space. However, recursive calls require stack memory.
| Case | Recursion Stack Space |
|---|---|
| Best / Balanced Partitions | O(log n) |
| Average Case | O(log n) |
| Worst Case | O(n) |
Therefore, the standard recursive implementation has O(log n) average auxiliary stack space and O(n) worst-case stack space.
12. Quick Sort Complexity Summary
| Case or Property | Complexity |
|---|---|
| Best Case Time | O(n log n) |
| Average Case Time | O(n log n) |
| Worst Case Time | O(n²) |
| Average Stack Space | O(log n) |
| Worst Stack Space | O(n) |
| Partition Auxiliary Space | O(1) |
13. Properties of Quick Sort
| Property | Description |
|---|---|
| Algorithm Type | Comparison-based sorting |
| Technique | Divide and Conquer |
| In-place | Yes, for the partitioning operation |
| Stable | No, standard implementation |
| Recursive | Yes, in the implementations shown |
| Average Time | O(n log n) |
| Worst Time | O(n²) |
Is Quick Sort Stable?
Standard Quick Sort is not stable. During partitioning, swapping elements can change the relative order of equal elements.
Is Quick Sort In-place?
Quick Sort is generally considered an in-place sorting algorithm because partitioning rearranges elements within the original array without requiring a separate array proportional to the input size.
However, recursive calls still require stack memory.
14. Pivot Selection Strategies
The pivot selection strategy can affect Quick Sort's performance. Common approaches include:
- First Element: Select the first element as the pivot.
- Last Element: Select the last element as the pivot.
- Middle Element: Select the middle element as the pivot.
- Random Pivot: Select a random element as the pivot.
- Median of Three: Select the median among the first, middle, and last elements.
15. Advantages of Quick Sort
- Has O(n log n) average-case time complexity.
- Usually performs well in practical applications.
- Uses in-place partitioning.
- Does not require an additional temporary array proportional to the input size.
- Has good cache performance in many implementations.
- Can be improved using randomized pivot selection.
16. Disadvantages of Quick Sort
- Its worst-case time complexity is O(n²).
- Standard Quick Sort is not stable.
- Poor pivot selection can produce unbalanced partitions.
- Recursive calls require stack memory.
- Highly unbalanced recursion can cause deep recursion and possible stack overflow.
17. Applications of Quick Sort
- General-purpose sorting of arrays.
- Sorting large collections in memory.
- Systems where average-case performance is important.
- Partition-based selection algorithms such as Quickselect.
- As a component in hybrid sorting implementations.
18. Quick Sort vs Merge Sort
| Feature | Quick Sort | Merge Sort |
|---|---|---|
| Technique | Divide and Conquer | Divide and Conquer |
| Best Case | O(n log n) | O(n log n) |
| Average Case | O(n log n) | O(n log n) |
| Worst Case | O(n²) | O(n log n) |
| Auxiliary Space | O(log n) average stack space | O(n) for standard array implementation |
| Stable | No, standard implementation | Yes, standard stable implementation |
| In-place | Generally yes, for partitioning | No, standard array implementation |
19. Common Mistakes
- Incorrect base condition: Use low < high to determine whether a partition needs sorting.
- Incorrect pivot position: In Lomuto Partition, return i + 1 after placing the pivot.
- Incorrect recursive ranges: Exclude the pivot index when using Lomuto Partition.
- Mixing partition schemes: Lomuto and Hoare Partition return different kinds of indices. Their recursive ranges must not be mixed.
- Incorrect comparison: Make sure the comparison matches the required sorting order.
- Ignoring worst-case complexity: Quick Sort can take O(n²) time with highly unbalanced partitions.
- Assuming Quick Sort is stable: Standard partition-based Quick Sort does not preserve the relative order of equal elements.
20. Interview Questions
- What is Quick Sort?
- Which algorithmic technique does Quick Sort use?
- What is a pivot element?
- What is partitioning in Quick Sort?
- Explain the Lomuto Partition scheme.
- Explain the Hoare Partition scheme.
- What is the average time complexity of Quick Sort?
- What is the worst-case time complexity of Quick Sort?
- When does the worst case occur?
- Is Quick Sort stable?
- Is Quick Sort in-place?
- What is the difference between Lomuto and Hoare Partition?
- How does randomized Quick Sort work?
- What is the recursion stack space complexity?
- How is Quick Sort different from Merge Sort?
21. Practice Problems
Problem 1: Sort an Array Using Quick Sort
Given an array of integers, sort it in ascending order using Quick Sort.
Input:
{8, 3, 1, 7, 0, 10, 2}
Output:
{0, 1, 2, 3, 7, 8, 10}
Problem 2: Sort an Array in Descending Order
Modify the partition logic to sort the array from largest to smallest.
Input:
{5, 2, 8, 1, 4}
Output:
{8, 5, 4, 2, 1}
Problem 3: Find the Kth Smallest Element
Given an array and an integer k, find the kth smallest element using a partition-based approach.
Input:
arr = {7, 10, 4, 3, 20, 15}
k = 3
Output:
7
Problem 4: Implement Randomized Quick Sort
Modify Quick Sort so that the pivot is selected randomly from the current partition.
Input:
{9, 4, 7, 3, 10, 5}
Output:
{3, 4, 5, 7, 9, 10}
Problem 5: Count Partition Operations
Modify the partition function to count how many comparisons are performed during partitioning.
Input:
{4, 2, 6, 1, 3}
Task:
Count comparisons during the first partition.
22. Summary
- Quick Sort is a comparison-based sorting algorithm.
- It follows the Divide and Conquer technique.
- It selects a pivot and partitions the array around it.
- It recursively sorts the portions on either side of the pivot.
- Its average and best-case time complexity is O(n log n).
- Its worst-case time complexity is O(n²).
- Its average recursion stack space is O(log n).
- Standard Quick Sort is generally in-place but not stable.
- Good pivot selection helps improve practical performance.