Quick Sort 🚄
Back to algorithms list.Functionality
QuickSort is an efficient, divide-and-conquer sorting algorithm that sorts a list by selecting a pivot element and partitioning the list into two sublists: one with elements smaller than the pivot and one with elements greater than the pivot. Instead of using additional memory for sublists, QuickSort rearranges elements directly within the original list. The process is recursively applied to the left and right sublists until the entire list is sorted.
Advantages
- High Efficiency: QuickSort has an average-case time complexity of O(n log n), making it one of the fastest sorting algorithms for large datasets.
- In-place Sorting: Unlike Merge Sort, QuickSort does not require extra memory for additional lists, making it space-efficient with an O(1) extra space complexity.
- Good Cache Performance: Due to its partitioning strategy, QuickSort often benefits from better cache locality compared to other sorting algorithms.
- Flexibility: Works well in most scenarios and can be optimized using different pivot selection strategies (e.g., median-of-three, random pivot).
Disadvantages
- Worst-Case Performance: In the worst case (e.g., when the smallest or largest element is always chosen as the pivot), the time complexity degrades to O(n²).
- Unstable: QuickSort is not a stable sorting algorithm, meaning it may change the relative order of equal elements.
- Recursive Calls: The recursive nature of QuickSort may lead to stack overflow for very large lists if not properly optimized with tail recursion or iterative partitioning.
Conclusion
QuickSort is one of the most widely used sorting algorithms due to its speed and space efficiency. While it can perform poorly with bad pivot choices, techniques like randomized pivot selection or hybrid approaches (e.g., switching to Insertion Sort for small sublists) help mitigate its weaknesses.
Source: Article about quicksort on wikipedia.org
Source code: github.com/danielnagel/algorithms