In: Computer Science
(C++)Order statistics: Write codes for Rand-Select (with linear expected running time) and Select (with linear worst-case running time). Test your two programs with an input array that is a random permutation of A = {1, 2, 3, …, 99, 100}
PARTITION(A, p, r)
x = A[r]
i = p
for k = p to r
if A[k] < x
i = i + 1
swap A[i] with A[k]
i = i + 1
swap a[i] with a[r]
return i
RANDOMIZED-PARTITION(A, p, r)
x = RANDOM(p, r)
swap A[x] with A[r]
return PARTITION(A, p, r)
RANDOMIZED-SELECT(A, p, r, i)
while true
if p == r
return p, A[p]
q = RANDOMIZED-PARTITION(A, p, r)
k = q - p + 1
if i == k
return q, A[q]
if i < k
r = q
else
p = q + 1
i = i - k
k-QUANTITLES-SUB(A, p, r, pos, f, e, quantiles)
if f + 1 > e
return
mid = (f + e) / 2
q, val = RANDOMIZED-SELECT(A, p, r, pos[mid])
quantiles[mid] = val
k = q - p + 1
for i = mid + 1 to e
pos[i] = pos[i] - k
k-QUANTILES-SUB(A, q + 1, r, pos, mid + 1, e, quantiles)
k-QUANTITLES(A, k)
num = A.size() / k
mod = A.size() % k
pos = num[1..k]
for i = 1 to mod
pos[i] = pos[i] + 1
for i = 1 to k
pos[i] = pos[i] + pos[i - 1]
quantiles = [1..k]
k-QUANTITLES-SUB(A, 0, A.length, pos, 0, pos.size(), quantiles)
return quantiles
MEDIAN(X, Y, n)
if n == 1
return min(X[1], Y[1])
if X[n / 2] < Y[n / 2]
return MEDIAN(X[n / 2 + 1..n], Y[1..n / 2], n / 2)
return MEDIAN(X[1..n / 2], Y[n / 2 + 1..n], n / 2)