What is the time complexity of the quicksort algorithm?

Algorithm Design Questions Medium



49 Short 51 Medium 39 Long Answer Questions Question Index

What is the time complexity of the quicksort algorithm?

The time complexity of the quicksort algorithm is O(n log n) on average and O(n^2) in the worst case scenario.

In the average case, quicksort divides the input array into two sub-arrays around a pivot element, and then recursively sorts these sub-arrays. The partitioning step takes O(n) time, and since the algorithm divides the array into two halves at each level of recursion, it results in a balanced binary tree of recursive calls. This leads to a time complexity of O(n log n) on average.

However, in the worst case scenario, when the chosen pivot is either the smallest or largest element in the array, quicksort can degenerate into a quadratic time complexity of O(n^2). This occurs when the partitioning consistently creates sub-arrays of size 0 and n-1, resulting in unbalanced recursive calls.

To mitigate the worst case scenario, various techniques can be employed, such as choosing a random pivot, using a median-of-three pivot selection, or implementing an optimized version of quicksort like introsort, which switches to a different sorting algorithm (such as heapsort) when the recursion depth exceeds a certain threshold. These techniques help ensure that the average time complexity of quicksort remains O(n log n).