Quick Sort in C++
Quick Sort Algorithm in C++ (Complete Implementation).
1#include <iostream>2using namespace std;34int partition(int arr[], int low, int high) {5 int pivot = arr[high];6 int i = low - 1;78 for (int j = low; j < high; j++) {9 if (arr[j] < pivot) {10 i++;11 swap(arr[i], arr[j]);12 }13 }14 swap(arr[i + 1], arr[high]);15 return i + 1;16}1718void quickSort(int arr[], int low, int high) {19 if (low < high) {20 int pi = partition(arr, low, high);2122 // Recursively sort elements before and after partition23 quickSort(arr, low, pi - 1);24 quickSort(arr, pi + 1, high);25 }26}2728void printArray(int arr[], int n) {29 for (int i = 0; i < n; i++) {30 cout << arr[i] << " ";31 }32 cout << endl;33}3435int main() {36 int arr[] = {64, 34, 25, 12, 22, 11, 90};37 int n = sizeof(arr) / sizeof(arr[0]);3839 cout << "Original array: ";40 printArray(arr, n);4142 quickSort(arr, 0, n - 1);4344 cout << "Sorted array: ";45 printArray(arr, n);4647 return 0;48}
Output
Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90
What's going on
The program sorts an array of integers using the Quick Sort algorithm. For example:
Quick Sort works by selecting a pivot, partitioning the array so elements smaller than pivot are on the left and larger on the right, then recursively sorting the partitions.
Header File Used
This header provides:
1#include <iostream>
Understanding Quick Sort
Algorithm Concept
:
1.
Choose Pivot
: Select an element as pivot (often last element)
2.
Partition
: Rearrange array so pivot is in correct position
3.
Recurse
: Recursively sort left and right partitions
Visual Example
:
[64, 34, 25, 12, 22, 11, 90]
Pivot: 90 (last element)
Partition: [64, 34, 25, 12, 22, 11] | 90
(all < 90) (pivot)
Recurse on [64, 34, 25, 12, 22, 11]
Pivot: 11
Partition: 11 | [64, 34, 25, 12, 22]
(pivot) (all > 11)
Continue recursively...
Function: partition()
int partition(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]);
}
1return i + 1;
How it works
:
Partition Process
(pivot = 90):
[64, 34, 25, 12, 22, 11, 90]
i = -1, j = 0: 64 < 90 → i=0, swap → [64, ...]
j = 1: 34 < 90 → i=1, swap → [64, 34, ...]
j = 2: 25 < 90 → i=2, swap → [64, 34, 25, ...]
...
After loop: [64, 34, 25, 12, 22, 11, 90]
Place pivot: [64, 34, 25, 12, 22, 11, 90] (pivot already at end)
Function: quickSort()
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
How it works
:
Understanding Partition
Partition Goal
:
Partition Index (pi)
:
Time and Space Complexity
Time Complexity
:
Space Complexity
: O(log n)
Stability
: Not Stable
When to Use Quick Sort
Best For
:
Not Recommended For
:
Important Considerations
Pivot Selection
:
Partition Balance
:
Recursive Calls
:
return 0;
This ends the program successfully.