I’m trying to understand the Select algorithm and I came across a good pivot VS a bad pivot . I can see that the algorithm is using Partition algorithm for separating the bigger elements on the right of
the pivot , and the smaller elements on the left of the pivot .
- But what does it mean a
bad pivot? - How can a
bad pivotthrow the total run time intoO(n^2)?
Thanks
The selection algorithm will be fast if it can discard huge chunks of the array at each step. A good pivot is one that for some definition of “a lot” causes the algorithm to discard “a lot” of the array elements. A bad pivot is one for which the algorithm discards very title of the array.
In the worst case, the pivot might be the largest or smallest element of the array. If this happens, then the algorithm will partition the elements in a way where one group of values is empty, since there will be either no elements less than the pivot or no elements greater than the pivot. This partitioning step takes time O(n), and will have to be run O(n) times, since each iteration decreases the size of the array by one. This degrades the algorithm runtime to O(n2). Interestingly, this is also the way to get quick sort to degenerate to time O(n2).
Hope this helps!