![]() ![]() If you are really worried about malicious users or you need to guarantee that the quicksort runs is O(n log n) then use the median of medians. If you are somewhat worried about malicious users giving you bad arrays to sort (used as a Denial of Service attack) then use random pivots. If there is a reasonable chance your data is sorted use the middle element or median of threes. If it is unlikely that the data will be sorted, and you are willing to accept O(n^2) in the rare cases when the array is sorted then use the leftmost or rightmost element. ![]() Typically, a lot slower than the above methods. Quick sort is now O(n log n) worst case !Ĭons: Complicated code. Pros: The pivot is guaranteed to be good. Use the median of medians method to select a pivot Still theoretically possible that it can degrade to O(n^2). Pros: Much harder for someone to construct an array that will cause it to degrade to O(n^2), if they don't know how you are choosing the random numbers.Ĭons: May be complicated to code. Still can degrade to O(n^2).Ĭhoose the pivot randomly (using a custom built random function): Harder for someone to construct an array that will cause it to degrade to O(n^2)Ĭons: Selecting a random pivot is fairly slow. Fairly easy for someone to construct an array that will cause it to degrade to O(n^2)Ĭhoose the pivot randomly (using built in random function): Pros: Fairly simple to code, reasonably fast to calculate, but slightly slower than the above methodsĬons: Still can degrade to O(n^2). Easy for someone to construct an array that will cause it to degrade to O(n^2) Pros: Simple to code, fast to calculate, but slightly slower than the above methodsĬons: Still can degrade to O(n^2). What are some techniques to choose a pivot ?Ĭhoose the left most or rightmost element.Ĭons: If the data is sorted or nearly sorted, quick sort will degrade to O(n^2) (A classic case is when the first or last element is chosen as a pivot and the data is already sorted, or nearly sorted) This happens if the pivot is consistently chosen so that all (or too many of) the elements in the array are than the pivot. On average quick sort runs in O(n log n) but if it consistently chooses bad pivots its performance degrades to O(n^2) Pivot selection is an important part of quick sort and there are many techniques, all with pros and cons. A single p and r pair point at the fifth element.
0 Comments
Leave a Reply. |