Quickselect algorithm

Suppose we want to know the k-th element of the array, how we would do?

  1. We would sort the array, with O(nlogn) for example
  2. Then we will get the element searched

But there’s a faster method using a similar idea of QuickSort. Let’s view the QuickSelect algorithm in pseudocode applied to the problem of find the kth element of an array.Integer KthElement(Sequence S, Integer k)

The idea is:

  1. Choose a random position in the array
  2. Partition the sequence in three sub-set: L of the elements that are Less of the element chosen, G of elements that are Greater and E of elements that are Equal
  3. Then if the L set has just k – 1 elements, in the E set we have the kth element anche we can return it
  4. Else we have other 2 possibilities: L is greater than our k or less, in both cases we run recursively but we will enter only in one of this two ways because if the L set is smaller than k it makes no sense to search the kth element there, so let’s search only on the greater set (setting k passed as parameter opportunely) and vice versa
  5. Finally return the result of the recursive call

Note that this algorithm does not handle the case in which we have repetition in the array, as for example:

In this case the first step will do (chosen 12 for example)

If we want to search for the 8th element of the array the repetition of 2 and 4 in the L set will alter the result because the algorithm at the first step, because L is 7 elements big, will return 12 as the 8th element while if we ordered the array

there’s no 8th element!