Selection Algorithm

Input: Sequence SS of nn numbers and an integer kk with 1kn1 \leq k \leq n.
Output: The kk-th smallest element in SS.

Sort S
return the element at position k

Run time O(nlog(n))O(n \log (n))

Here's an algorithm without sorting. Assume that all numbers are different. Assume that there is a constant 0<α<10 < \alpha < 1 such that in Select (S, p), it is always to choose a pivot pp satisfying S<an|S_<| \leq a n and S>an|S_>| \leq a n

def Select (S, k)
if |S| = 1:
return the only element in S
else
Choose an element p in S (called the pivot)
Split S into S_<, S_=, and S_>
if (k <= |S_<|):
Run Select(S_<, k)
elif (k > |S_<| + |S_=|):
Run Select(S_>, k - |S_<| - |S_=|)
else:
return p

To find a good pivot pp:

  1. Divide the input scenario in to n5\frac{n}{5} groups, each of size 5.
  2. For i=1,2,...,n/5i = 1, 2, ..., n/5, compute the median of the ithi-th group, call this median mim_i.
  3. Compute the median pp of m1,m2,...,mn/5m_1, m_2, ..., m_{n/5}.
  4. Run Select (S, k) using the pp of Step 3 as the pivot.

Time complexity is T(n)=T(1/5n)+T(7/10n)+O(n)=O(n)T(n) = T(1/5 n) + T(7/10 n) + O(n) = O(n)