Sorting

Quicksort

Size:15
Visualizer is loading, please wait...
Execution Narrative
Step 1 of 93Start
Line 1
Starting Quick Sort on array of 15 elements.
Comparisons0
Swaps0
Operations0

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

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(n log n)O(n log n)O(n²)O(log n)
ExplanationOptimal 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.

Compare trade-offs and complexity across complementary tools in AlgoViz.