š Quick Sort (with Running Time Analysis)
1ļøā£ Introduction
Quick Sort is a highly efficient Divide-and-Conquer sorting algorithm.
š¹ Idea
- Select a pivot element
- Partition the array into:
- Elements less than pivot
- Elements greater than pivot
- Recursively sort the partitions
It is widely used due to its excellent average-case performance.
2ļøā£ Working Principle (Divide & Conquer)
š¹ Steps
- Divide: Choose a pivot and partition the array
- Conquer: Recursively apply Quick Sort on subarrays
- Combine: No extra work needed (already sorted in place)
3ļøā£ Algorithm (Quick Sort)
š¹ Pseudocode
QuickSort(A, low, high):
if low < high:
p = Partition(A, low, high)
QuickSort(A, low, p-1)
QuickSort(A, p+1, high)
š¹ Partition Function (Lomuto Method)
Partition(A, low, high):
pivot = A[high]
i = low - 1
for j = low to high-1:
if A[j] <= pivot:
i = i + 1
swap A[i] and A[j]
swap A[i+1] and A[high]
return i+1
4ļøā£ Example (Step-by-Step)
š¹ Given Array:
A = [10, 7, 8, 9, 1, 5]
š¹ Step 1: Choose Pivot (5)
Partition:
[1, 5, 8, 9, 10, 7]
š¹ Step 2: Left Subarray [1]
Already sorted
š¹ Step 3: Right Subarray [8, 9, 10, 7]
Pivot = 7
[7, 8, 9, 10]
š¹ Final Sorted Array:
[1, 5, 7, 8, 9, 10]
ā Sorted successfully
5ļøā£ Running Time Analysis
š¹ Recurrence Relation
Best / Average Case:
[
T(n) = 2T(n/2) + O(n)
]
Worst Case:
[
T(n) = T(n-1) + O(n)
]
6ļøā£ Time Complexity
| Case | Complexity |
|---|---|
| Best Case | O(n log n) |
| Average Case | O(n log n) |
| Worst Case | O(n²) |
š Worst case occurs when:
- Array is already sorted
- Poor pivot selection
7ļøā£ Space Complexity
- Recursive stack:
- Best/Average ā O(log n)
- Worst ā O(n)
8ļøā£ Recursion Tree Analysis (Concept)
š¹ Balanced Partition
- Depth = log n
- Work per level = n
Total:
[
O(n \log n)
]
š¹ Unbalanced Partition
- Depth = n
- Work per level = n
Total:
[
O(n²)
]
9ļøā£ Characteristics of Quick Sort
ā In-place sorting
ā Very fast in practice
ā Not stable
ā Performance depends on pivot
š Advantages
- Faster than Merge Sort in practice
- Requires less memory
- Good cache performance
- Widely used in real systems
1ļøā£1ļøā£ Disadvantages
- Worst-case O(n²)
- Not stable
- Recursive overhead
1ļøā£2ļøā£ Comparison with Merge Sort
| Feature | Quick Sort | Merge Sort |
|---|---|---|
| Time (Avg) | O(n log n) | O(n log n) |
| Worst Case | O(n²) | O(n log n) |
| Space | O(log n) | O(n) |
| Stability | No | Yes |
š Conclusion
Quick Sort is one of the fastest sorting algorithms in practice, especially for large datasets.
Its efficiency depends on good pivot selection, making average performance excellent but worst-case performance poor.
š Exam Tip
š Always include:
- Partition concept
- Recurrence relation
- Time complexity cases
- Example
