Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Second largest number in array at most n+log₂(n)−2 comparisons [closed]

Tags:

algorithm

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.

like image 221
Amit Deshpande Avatar asked Mar 27 '12 12:03

Amit Deshpande


People also ask

How would you find the second largest element in an array using minimum No of 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.

How do you find the second largest value of an array when grouped by another array?

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.

How many comparisons are needed to find the largest element in a list of n?

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.


1 Answers

  1. Start with comparing elements of the n element array in odd and even positions and determining largest element of each pair. This step requires n/2 comparisons. Now you've got only n/2 elements. Continue pairwise comparisons to get n/4, n/8, ... elements. Stop when the largest element is found. This step requires a total of n/2 + n/4 + n/8 + ... + 1 = n-1 comparisons.
  2. During previous step, the largest element was immediately compared with log₂(n) other elements. You can determine the largest of these elements in log₂(n)-1 comparisons. That would be the second-largest number in the array.

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.

like image 156
Evgeny Kluev Avatar answered Sep 21 '22 22:09

Evgeny Kluev