Quick sort is a highly efficient sorting algorithm that uses a divide-and-conquer approach. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.
Implementation Details
Here are some common ways to implement quick sort:
In-Place Quick Sort: This version of quick sort sorts the array in place, meaning that it doesn't require any additional storage space beyond the input array.
def quick_sort(arr): if len(arr) <= 1: return arr 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 quick_sort(left) + middle + quick_sort(right)
Iterative Quick Sort: This version of quick sort uses an explicit stack to simulate the recursion stack.
def iterative_quick_sort(arr): stack = [(0, len(arr) - 1)] while stack: start, end = stack.pop() if start >= end: continue pivot = arr[(start + end) // 2] left, right = start, end while left <= right: while arr[left] < pivot: left += 1 while arr[right] > pivot: right -= 1 if left <= right: arr[left], arr[right] = arr[right], arr[left] left, right = left + 1, right - 1 stack.append((start, right)) stack.append((left, end)) return arr
Why Use Quick Sort?
Quick sort is preferred over other sorting algorithms due to its efficiency. It has an average time complexity of O(n log n) and a worst-case time complexity of O(n^2), although the worst case is rare in practice.
Learn More
For more information on sorting algorithms and their implementations, check out our Sorting Algorithms Guide.