Show that the second smallest of
$n$ elements can be found with$n + \lceil \lg n\rceil - 2$ comparisons in the worst case.
Divide the elements into the leaves of a binary tree. In each node, we compare the minimum values of its two sub-trees, then in the root node we know which is the smallest element using
def find_second_smallest(a, l, r):
if l + 1 == r:
return a[l], []
mid = (l + r + 1) // 2
min_l, lst_l = find_second_smallest(a, l, mid)
min_r, lst_r = find_second_smallest(a, mid, r)
if min_l <= min_r:
min_val, lst = min_l, lst_l + [min_r]
else:
min_val, lst = min_r, lst_r + [min_l]
if l == 0 and r == len(a):
idx = 0
for i in range(1, len(lst)):
if lst[i] < lst[idx]:
idx = i
return lst[idx]
return min_val, lst
Prove the lower bound of
$\lceil 3n/2 \rceil - 2$ comparisons in the worst case to find both the maximum and minimum of$n$ numbers.
If
comparisons.
If
comparisons.