In quick sort we can choose a pivot value in different ways. Randomly choose a pivot value is one of that. It says that when we choose the pivot value randomly , it minimize tha chance of having O(n^2). Can anyone explain how does it happen? Are there any disadvantages?
Share
Both random and non-random pick produce an algorithm whose expected run time is Theta(n*log(n)), if the expected value is averaged over all possible inputs (permutations).
In practice not all input permutations are equally probable. In particular you often get sorted or nearly sorted arrays when pick-first gives Theta(n^2) complexity. On top of that if your picking algorithm is deterministic, an attacker can craft a nasty permutation to make your algorithm quadratic, thus achieving denial of service.
Picking random element as the pivot guards against these non-random cases.