The worst case in QuickSort occurs when the pivot element chosen at each step consistently results in highly unbalanced partitions. This happens typically when the pivot is either the smallest or largest element in the array. In practical terms, this situation arises when:
- The array is already sorted, either in ascending or descending order, and the pivot chosen is an extreme element (e.g., first or last element).
- All elements of the array are the same.
- The pivot selection method always picks a very unbalanced partition, such as always choosing the highest or lowest element as pivot.
In this worst case, the time complexity degrades to O(n2)O(n^2)O(n2), because each partitioning only reduces the problem size by one element instead of roughly halving it. To avoid this worst-case, techniques such as choosing a random pivot, the median of three elements, or other pivot selection strategies are used to encourage more balanced partitions and optimal average performance of O(nlogā”n)O(n\log n)O(nlogn).