pseudo
pseudo
1
Algorithm 2 DSelect Algorithm
Require: An array A of length n and an integer i (1-based index).
Ensure: The i-th smallest element in A.
1: function DSelect(A, n, i)
2: if n == 1 then
3: return A[1]
4: end if
5: Split A into ⌈n/5⌉ groups of 5 elements each
6: Let C be an array of medians of each group
7: p ← DSelect(C, ⌈n/5⌉, ⌈⌈n/5⌉/2⌉) ▷ Find median of medians
8: Partition A into L (elements ≤ p) and R (elements > p)
9: Let j be the index of p in the partitioned array
10: if i == j then
11: return p
12: else if i < j then
13: return DSelect(L, j − 1, i)
14: else
15: return DSelect(R, n − j, i − j)
16: end if
17: end function