Quick Sort: Algorithm & Implementation
1️⃣ What is Quick Sort?
🔹 Quick Sort is a divide-and-conquer sorting algorithm.
🔹 It selects a pivot element and partitions the array so that:
- Elements smaller than pivot go to the left.
- Elements greater than pivot go to the right.
🔹 The process repeats recursively until the array is sorted.
✅ Time Complexity
Case | Complexity |
---|---|
Best Case (Balanced Partitioning) | O(n log n) |
Average Case | O(n log n) |
Worst Case (Already Sorted, Unbalanced Partitioning) | O(n²) |
✅ Space Complexity
- O(log n) (for recursive stack calls)
✅ Is it Stable?
❌ No (Relative order of equal elements may change)
2️⃣ How Quick Sort Works
🔹 Select a pivot element.
🔹 Partition the array so that:
- Left part contains elements < pivot
- Right part contains elements > pivot
🔹 Recursively sort left and right partitions.
Step-by-Step Example
📝 Input: [10, 80, 30, 90, 40, 50, 70]
Pivot = 70 (can be any element, commonly last, first, or random)
Step | Array State | Partitioning Around Pivot |
---|---|---|
1 | [10, 30, 40, 50, 70, 90, 80] | Pivot 70 placed correctly |
2 | `[10, 30, 40, 50] | 70 |
3 | `[10, 30] | 40 |
🔹 Final Sorted Array: [10, 30, 40, 50, 70, 80, 90]
3️⃣ Quick Sort Algorithm
🔹 Pseudocode
4️⃣ Quick Sort Implementation in C
🔹 Output
5️⃣ Advantages & Disadvantages
✅ Advantages
✔ Faster than other O(n²) algorithms like Selection and Insertion Sort.
✔ Efficient for large datasets (O(n log n) in average case).
✔ In-place sorting (O(log n) extra space for recursion).
❌ Disadvantages
❌ Worst case O(n²) if pivot selection is poor (already sorted or reversed).
❌ Not stable (relative order of equal elements may change).
❌ Uses recursion, which may cause stack overflow for large arrays.
6️⃣ When to Use Quick Sort?
🔹 Best for large datasets (better than Bubble, Insertion, or Selection Sort).
🔹 Useful when in-place sorting is required (O(1) extra space).
🔹 Not ideal if stable sorting is required (use Merge Sort instead).
💡 For best performance, use a randomized or median pivot selection! 🚀