Answer-E
Think about partition method in quick sort. it places pivot to correct location and return the index of pivot element. Now suppose partition returns k then can you tell me what is kth smallest element ?
Yes that’s right – Pivot element is kth smallest element. (Think about it).
Select also does same thing. 𝖲𝖾𝗅𝖾𝖼𝗍(S,r) will not only return rth smallest element but it also places rth smallest to its correct position just like pivot. (if their implementation of 𝖲𝖾𝗅𝖾𝖼𝗍(S,r) is not doing so then I will find rth smallest and i will rearrange my array manually but lets not worry about it).
Now comes main part. How to implement 𝖬𝗎𝗅𝗍𝗂𝖲𝖾𝗅𝖾𝖼𝗍() efficiently ?
I am taking an example to explain idea. Suppose R = {2,4,6,8,10,12}. which means you want 2nd smallest, 4th smallest, 6th smallest and so on.
I will pick middle element of R which is 8 and i will search for 8th smallest first. We can do it in O(S).
Here is an crucial observation-
Once we get 8th smallest then how our array looks like ? – 8th smallest is at its correct position. if 8th smallest is at its correct position then where is 4th smallest ? – left side of array of 8th smallest. where is 12th smallest? – right side of array of 8th smallest.
Now I will search for 4th smallest. Now do i need to search 4th smallest in entire array ? – No, I can just search in left side of 8th smallest. Suppose there are K elements on left side and |S|-K elements on right side.
I will find 4th smallest in left side and 10th smallest in right side. but total only |S| comparisions (K for 4th smallest and |S|-K for 10th smallest). This says that we can find 2 elements in |S| comparisons.
After this my array is having 4th smallest, 8th smallest and 10th smallest at its correct position. basically i can divide my array in 4 parts now.
1st part – left side of 4th smallest
2nd part – between 4th smallest and 8th smallest
3rd part – between 8th smallest and 10th smallest
4th part- after 10th smallest.
How many element i can find in just |S| comparisons now ? – yes 4 elements. Anything having rank smaller than 4 i will search in first part only and so on.
Whats the pattern ?
Initially We took |S| comparisions for 1 element (8th smallest)
then we took |S| comparisions for 2 elements (4th and 10th smallest)
then we take |S| comparisions for 4 elements.
Just draw a tree. Start with array, then divide it into 2 parts and then 4 parts and so on.
Since there are total |R| elements so tree height will be log|R| and at each level we are spending |S| comparisions.
total |S|log|R| comparisons. If you do it carefully then there will be log|R|+1 levels. giving you E as answer.