Efficient Approach: Follow the steps below to solve the problem:
Find the largest element from the given array and keep track of all the elements compared with the largest element.
Split the current array into two equal length subarrays.
For each subarray, recursively find the largest element, and return an array in which the first index contains the length of this array, second index element contains the largest element and the remaining array contains the elements with which the largest element has been compared.
Now, from the two arrays returned by both the subarrays, compare the largest element of both the subarrays and return the array that contains the largest of the two.
The final array returned by the findLargest() contains its size in the first index, the largest element of the array at the second index, and the elements compared with the largest element in the remaining indices. Repeat the above steps using the findLargest() to find the second largest element of the array from the list of compared elements.
Analysis Of Algorithm: It is clearly visible from the algorithm that the time complexity of the findLargest() algorithm is O(N) [N: size of the array] Hence, (N-1)comparisons are performed. Now, the size of the array returned by findLargest() is log2(N) + 2, out of which log2(N) elements are the ones with which the largest element is compared. Hence, to find the second largest element, the largest among these log2(N) elements is calculated using log2(N) – 1 comparisons.
Therefore, the total number of comparisons = N – 1 + log2(N) – 1 = N + log2(N) – 2
Below is the implementation of the above approach:
Please Login to comment...