Quick Sort
📌 Definition:
Quick Sort is a highly efficient divide and conquer sorting algorithm. It works by selecting a pivot element, then
partitioning the array such that:
• Elements less than the pivot go to its left
• Elements greater than the pivot go to its right
Then it recursively sorts the left and right parts.
🔍 How It Works:
1. Choose a Pivot:
Pick an element as the pivot (can be first, last, random, or median).
2. Partition:
Rearrange the array so that:
o Elements smaller than pivot come before it
o Elements greater than pivot come after it
3. Recursively Apply:
Apply the same steps to the left and right subarrays.
🧠 Example (Array: [10, 80, 30, 90, 40, 50, 70])
Let's say the last element is chosen as the pivot:
1. Pivot = 70
2. After partition: [10, 30, 40, 50] 70 [90, 80]
3. Recursively sort left and right of 70
4. Final sorted array: [10, 30, 40, 50, 70, 80, 90]
⏱️ Time Complexity:
Case Time
Best O(n log n)
Average O(n log n)
Worst O(n²)
• Worst case occurs when the pivot is the smallest/largest and partitions are unbalanced (e.g., sorted array).
💾 Space Complexity:
• O(log n) auxiliary space for recursive calls (for in-place version).
⚙️ Key Properties:
✅ Advantages:
• Very fast in practice for large datasets
• In-place (no extra space needed)
• Simple to implement with good pivot strategies (e.g., randomized pivot)
⚠️ Disadvantages:
• Not stable by default
• Worst-case time is O(n²) if pivot selection is poor
• Recursive stack can lead to stack overflow for very large arrays
Quick Sort Implementation in C
#include <stdio.h>
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[100], R[100]; // Temporary arrays (assuming max size)
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0; j = 0; k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}
while (i < n1)
arr[k++] = L[i++];
while (j < n2)
arr[k++] = R[j++];
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {5, 2, 9, 1, 3, 6};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
printArray(arr, n);
mergeSort(arr, 0, n - 1);
printf("Sorted array:\n");
printArray(arr, n);
return 0;
}