Quick Sort
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>
i = 0; j = 0; k = l;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
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;
}