You are given as input an unsorted array of n distinct numbers, where n is a power of 2. Give an algorithm that identifies the second-largest number in the array, and that uses at most n+log₂(n)−2 comparisons.
In short, the Minimum Comparisons to find Second Largest Element or Second Smallest Element is N + logN - 2 comparisons . Hence, if there are 1024 elements, then we need at least 1024 + 10 - 2 = 1032 comparisons.
Approach: The approach is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element in the remaining excluding the previous greatest.
this takes n-1 comparisons and each element is involved in comparison at most log n times. You will find the largest element as the winner.
Example: array of 8 numbers [10,9,5,4,11,100,120,110].
Comparisons on level 1: [10,9] ->10 [5,4]-> 5, [11,100]->100 , [120,110]-->120.
Comparisons on level 2: [10,5] ->10 [100,120]->120.
Comparisons on level 3: [10,120]->120.
Maximum is 120. It was immediately compared with: 10 (on level 3), 100 (on level 2), 110 (on level 1).
Step 2 should find the maximum of 10, 100, and 110. Which is 110. That's the second largest element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With