Quick Sort is a highly efficient divide-and-conquer sorting algorithm. It is widely used due to its excellent performance in practice and ability to sort in-place. Quick Sort divides the array into smaller parts by selecting a pivot element, then rearranges (or “partitions”) the elements so that:
The process is repeated recursively for the left and right parts until the entire array is sorted.
Case | Time Complexity |
---|---|
Best | O(n log n) |
Average | O(n log n) |
Worst | O(n²) |
#include <iostream>
using namespace std;
// Function to swap two elements
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
// Partition function
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose last element as pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}
// Quick Sort function
void quickSort(int arr[], int low, int high) {
if (low < high) {
// Partition the array
int pi = partition(arr, low, high);
// Sort the sub-arrays
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Utility function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Main function
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array:\n";
printArray(arr, n);
quickSort(arr, 0, n - 1);
cout << "Sorted array:\n";
printArray(arr, n);
return 0;
}
Original array:
10 7 8 9 1 5
Sorted array:
1 5 7 8 9 10
Let’s sort:
[10, 7, 8, 9, 1, 5]
After partitioning:
[1, 5, 8, 9, 10, 7]
→ Pivot 5 is at its correct position
[1]
→ already sorted[8, 9, 10, 7]
Result:
[1, 5, 7, 9, 10, 8]
[9, 10, 8]
[1, 5, 7, 8, 9, 10]
[1, 5, 7, 8, 9, 10]