Data Structures and Algorithms
Which is a typical case in which quicksort takes O(n²) time?
- AThe data is in random order and the pivot is chosen at random
- BThe number of data items is a power of two
- CThe data is already sorted and the first element is always used as the pivot
Show answer and explanation
Answer: C. The data is already sorted and the first element is always used as the pivot
Quicksort splits the elements into those smaller and those larger than the pivot, then splits each part again. If the data is already sorted and the first element is always the pivot, the pivot is the minimum every time and each split is lopsided, with zero elements on one side and all the rest on the other, so it makes n(n−1)/2 comparisons (4,950 for n = 100). Choosing the pivot at random or as the median of three values makes a long run of lopsided splits extremely unlikely. The number of items has nothing to do with this.
- A. With a random pivot, lopsided splits are extremely unlikely to keep happening, and it averages O(n log n).
- B. Whether the count is a power of two has nothing to do with lopsided splits.
- C. Correct. The pivot is the minimum every time, so the splits are extremely lopsided.