Quick Sort
Quick sort is a divide-and-conquer sorting algorithm that picks a pivot element, partitions the array so smaller items go left and larger items go right, and recursively sorts both sides. It averages O(n log n) time and O(log n) stack space, with O(n²) wo
Theory & Explanation
Quick Sort: Definition, Stepwise Working, Complexity & Code
1. Definition & Key Characteristics
Quick Sort is a fast, comparison-based sorting algorithm based on the Divide and Conquer paradigm. It selects an element called a pivot and partitions the array around the pivot so that elements smaller than (or equal to) the pivot are placed on its left and elements greater than the pivot are placed on its right. The pivot then sits at its final sorted position, and the algorithm recursively applies the same process to the left and right sub-arrays.
- In-Place Sorting: Partitioning rearranges elements within the array using a few index/swap variables, requiring only
O(log2 n)average call-stack space (andO(n)in the worst case for skewed recursion). - Not Stable (in Standard Partition): Swapping elements across a pivot can change the relative order of equal keys.
- Cache-Friendly & Fast in Practice: Operates sequentially on contiguous memory and typically outperforms Merge Sort in practice for in-memory arrays despite its
O(n2)worst case. - Pivot Selection Matters: Choosing the pivot as the first, last, middle, or random element (or median-of-three) affects partition balance and worst-case avoidance.
2. How Quick Sort Works (Step-by-Step Algorithm — Lomuto Partition Scheme)
- Base Case: If
low >= high(sub-array has 0 or 1 element), return immediately—it is already sorted. - Choose Pivot: Select the last element as pivot:
pivot = arr[high]. - Initialize Partition Boundary: Set
i = low - 1(tracks the end of elements smaller than or equal topivot). - Scan & Swap: Loop
jfromlowtohigh - 1:- If
arr[j] <= pivot, incrementi = i + 1and swaparr[i]witharr[j].
- If
- Place Pivot: After the loop ends, swap
arr[i + 1]witharr[high](the pivot). Now the pivot is at its final sorted indexpi = i + 1. - Recurse: Recursively call
quickSort(arr, low, pi - 1)andquickSort(arr, pi + 1, high).
3. Step-by-Step Example & Graphical Representation
Sort arr = [30, 10, 50, 20, 40] (n = 5) in ascending order using pivot = last element:
- Call 1 on
[30, 10, 50, 20, 40](low = 0, high = 4,pivot = 40):30 ≤ 40→i = 0, swap30with30.10 ≤ 40→i = 1, swap10with10.50 > 40→ no swap.20 ≤ 40→i = 2, swap50with20→[30, 10, 20, 50, 40].- Swap
arr[i + 1](50at index 3) withpivot(40at index 4) →[30, 10, 20, 40, 50]. - 40 is now fixed at index 3! Left sub-array:
[30, 10, 20](indices0..2); Right sub-array:[50](index4, size 1 → already sorted).
- Call 2 on Left Sub-array
[30, 10, 20](low = 0, high = 2,pivot = 20):30 > 20→ no swap;10 ≤ 20→i = 0, swap30with10→[10, 30, 20].- Swap
arr[1](30) withpivot(20) →[10, 20, 30]. - 20 is fixed at index 1! Left
[10]and Right[30]are single elements, so the entire array becomes[10, 20, 30, 40, 50].
Graphical Representation: Stepwise Partitioning of Quick Sort on [30, 10, 50, 20, 40]
4. Time & Space Complexity Analysis
| Case | Condition | Recurrence | Time Complexity |
|---|---|---|---|
| Best Case | Pivot always splits the array into two nearly equal halves | T(n) = 2T(n/2) + O(n) |
O(n log2 n) |
| Average Case | Randomly ordered elements (balanced splits on average) | T(n) ≈ T(k) + T(n - k - 1) + O(n) |
O(n log2 n) |
| Worst Case | Pivot repeatedly gives maximally skewed splits (e.g., sorted/reverse array with fixed end pivot) | T(n) = T(n - 1) + O(n) |
O(n2) |
Auxiliary Space Complexity: O(log2 n) average recursion stack space; O(n) in the worst case (can be kept O(log2 n) worst-case stack by recursing on the smaller partition first and iterating on the larger one).
5. C Program: Quick Sort
#include <stdio.h>
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
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; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1; // Final sorted index of pivot
}
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);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {30, 10, 50, 20, 40};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array (Ascending): ");
printArray(arr, n);
return 0;
}
Expected Output (C):
Original array: 30 10 50 20 40
Sorted array (Ascending): 10 20 30 40 50
6. Python Program: Quick Sort
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort(arr, low=0, high=None):
if high is None:
high = len(arr) - 1
if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi - 1)
quick_sort(arr, pi + 1, high)
return arr
if __name__ == "__main__":
data = [30, 10, 50, 20, 40]
print("Original array:", data)
sorted_data = quick_sort(data[:])
print("Sorted array (Ascending):", sorted_data)
Expected Output (Python):
Original array: [30, 10, 50, 20, 40]
Sorted array (Ascending): [10, 20, 30, 40, 50]