DrawCode Algorithm Visualizer • Sorting • Medium

Quick Sort

Tags: Sorting, Divide and Conquer, Partition, In-Place

1. One-Liner

Quick Sort chooses a pivot, partitions the array into elements ≤ pivot and > pivot, then recursively sorts each side.


2. The Problem It Solves

Fast in-place sorting for general data with excellent average performance; widely used in libraries (often combined with Introsort / Dual-Pivot variants).


3. The Core Idea

Pick a referee (pivot); everyone shorter goes left, taller goes right — the referee stands in their final sorted position; repeat on each side.


4. How It Works (Step-by-Step)

StepWhat Happens
1.Choose pivot (last element, median-of-three, random)
2.Partition: reorder range so pivot ends at index p
3.Recursively sort [lo, p-1] and [p+1, hi]
4.Base: lo >= hi

5. Dry Run Example

[3, 8, 1, 5] with pivot 5: after partition something like [3, 1, 5, 8] — 5 is in place; sort [3,1] → [1,3].


6. Key Properties

PropertyValue
In-placeTypical Lomuto/Hoare use O(log n) stack
StableNo
Random pivotReduces worst-case on structured input

7. Where It Is Used

Company / SystemHow They Use It
C++ std::sortIntrosort (Quick + Heap fallback)
Java primitivesDual-pivot QuickSort

8. Interview Tips

Master partition invariants; mention median-of-three, random pivot, Introsort; worst-case vs Merge.


9. Comparison with Other Algorithms

AlgorithmAvg timeWorstStable
QuickO(n log n)O(n²)No
MergeO(n log n)O(n log n)Yes
HeapO(n log n)O(n log n)No

10. Complexity

MetricValue
Time (Best)O(n log n)
Time (Average)O(n log n)
Time (Worst)O(n²) naive pivot
SpaceO(log n) stack typical
Stable?No

Implementation Example (PYTHON)

def quick_sort(arr):
    def partition(lo, hi):
        p = arr[hi]
        i = lo
        for j in range(lo, hi):
            if arr[j] <= p:
                arr[i], arr[j] = arr[j], arr[i]
                i += 1
        arr[i], arr[hi] = arr[hi], arr[i]
        return i
    def qs(lo, hi):
        if lo >= hi:
            return
        pi = partition(lo, hi)
        qs(lo, pi - 1); qs(pi + 1, hi)
    qs(0, len(arr) - 1)
    return arr

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer