SORT5
Suppose you are given 25 distinct integers and a function, SORT5, that can sort five integers at a time. Compute the largest, second-largest, and third-largest integers among those 25 integers using SORT5 function and minimize the number of calls to SORT5.
Reference: EPI python, page 200
Solution:
Idea: (6 sorting in total)
Split the 25 integers into 5 groups randomly, each group has 5 integers.
Sort 5 groups individually.
let m1,m2,m3,m4,m5 be the largest integer in each group, sort these 5 integers. Suppose we have m1>m2>m3>m4>m5 . Then m1 is the largest integer.
To get the second largest integer, m2 is a candidate, and second largest value in the 1st group a1 is another candidate.
To get the third largest integer, m2,m3 are candidates, second largest value in the 1st group a1 , third largest value in the 1st group a2, and second largest integer in the second group b1 are also candidates. Thus we need to sort a1,a2,m2,b1,m3 to get the second largest and third largest.
Last updated