The worst case in QuickSort occurs when partitioning repeatedly produces highly unbalanced splits, such as one subarray with 0 elements and the other with n-1 elements.

This happens typically with already sorted or reverse-sorted arrays if the pivot is always chosen as the first or last element, leading to O(n²) time complexity instead of the average O(n log n).

Key Triggers for Worst Case

  • Sorted or Reverse-Sorted Input : When the array is already ordered (ascending/descending), selecting endpoints as pivots creates a skewed recursion tree.
  • All Elements Identical : Repeated partitioning yields empty partitions on one side.
  • Poor Pivot Selection : Fixed choices like first/last element fail on adversarial data; random or median-of-three pivots mitigate this.

Visual Example: Sorted Array Breakdown

Consider sorting with first-element pivot:

  1. Pivot=1 → Left: [] (empty), Right: → 4 comparisons
  1. Pivot=2 → Left: [], Right: → 3 comparisons
  1. Continues degenerating to n(n-1)/2 total work.

In contrast, balanced pivots (e.g., median) halve arrays each step for efficiency.

Scenario| Time Complexity| Partition Balance| Example Pivot Strategy
---|---|---|---
Worst| O(n²)| 0 & n-1| First/Last element 16
Average| O(n log n)| ~n/2 each side| Random/Median-of-3 35
Best| O(n log n)| Perfect halves| Ideal pivot choice 7

Mitigation Strategies in Practice

Modern implementations avoid pure worst-case via:

  • Randomized Pivots : Probability of bad splits drops exponentially.
  • Median-of-Three : Pick median of first/middle/last for better balance.
  • Hybrid with Insertion Sort : Switch for small subarrays (<10 elements) to cut recursion overhead.

"Worst case occurs when subarrays are completely unbalanced—0 elements on one side, n-1 on the other."

TL;DR : QuickSort's nightmare is unbalanced partitions from bad pivots on sorted data, but smart choices keep it fast in real-world use (as of 2026 trends in DSA discussions).

Information gathered from public forums or data available on the internet and portrayed here.