Problem Statement
QuickSort is a comparison-based sorting algorithm that divides an array into two sub-arrays: elements less than the pivot and elements greater than the pivot. It then recursively sorts these sub-arrays.
Algorithmic Approach / Logic
The QuickSort algorithm follows these steps:
1. **Choose a Pivot**: Select an element from the array to act as the pivot. The choice of pivot can affect performance, so common strategies include picking the first, last, middle, or random element. 2. **Partitioning**: Rearrange the array such that all elements less than the pivot come before it, and all elements greater than the pivot come after it. This is done in-place to minimize space usage. 3. **Recursion**: Apply the above steps recursively to the sub-arrays formed by the partitioning.Code Implementation (Python)
def quicksort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
Complexity Analysis
Time Complexity:
- Best Case: O(n log n) when the chosen pivot divides the array into two nearly equal sub-arrays. - Average Case: O(n log n) - Worst Case: O(n^2) if the smallest or largest element is always chosen as the pivot.Space Complexity:
- O(log n) due to the recursion stack space used for partitioning and sorting sub-arrays.