Selection Algorithm
Input: Sequence of numbers and an integer with .
Output: The -th smallest element in .
Sort Sreturn the element at position k
Run time
Here's an algorithm without sorting. Assume that all numbers are different. Assume that there is a constant such that in Select (S, p), it is always to choose a pivot satisfying and
def Select (S, k)if |S| = 1:return the only element in SelseChoose 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 :
- Divide the input scenario in to groups, each of size 5.
- For , compute the median of the group, call this median .
- Compute the median of .
- Run Select (S, k) using the of Step 3 as the pivot.
Time complexity is