Overview & Concept
Quick Sort (Quicksort) is an in-place divide-and-conquer algorithm that partitions arrays around a pivot element into smaller and larger subarrays, achieving O(n log n) expected time.
How It Works
Pivot Selection: Select a pivot element.
Lomuto or Hoare Partitioning: Move items smaller than pivot left, and larger items right.
Recursive Divide: Recurse on left and right sub-ranges.
In-Place Execution: Minimal auxiliary memory usage.
Step-by-Step Execution
1. Choose PivotDesignate pivot value.
2. Partition ArraySwap elements relative to pivot threshold.
3. Place PivotDrop pivot into its permanent sorted index.
4. Recurse SubarraysSort left and right halves.
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n log n) | O(n log n) | O(n²) | O(log n) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
Algorithm Logic
procedure quickSort(A, low, high):
if low >= high: return
pivot = A[high]
i = low - 1
for j = low to high - 1:
if A[j] <= pivot: i++; swap(A[i], A[j])
end for
swap(A[i + 1], A[high]) // place pivot
quickSort(A, low, pivotIdx - 1)
quickSort(A, pivotIdx + 1, high)Algorithmic Invariants
- Partition Invariant: All elements left of pivot are ≤ pivot; all elements right are ≥ pivot.
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.
Advantages & Disadvantages
Key Advantages
- •Fastest average in-memory comparison sort.
- •In-place with O(log n) stack frames.
Trade-offs & Limitations
- •Unstable; O(n²) worst case without randomized or median-of-three pivot.
Real-World Applications
C++ std::sort
Standard template library introsort implementation.
Decision Guide: When to Use
Ideal Scenarios
- ✓General-purpose fast in-memory sorting.
Consider Alternatives When
- ✕When stability is strictly necessary.
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.