In: Computer Science
We are given an array of n numbers A in an arbitrary order. Design an algorithm to find the largest and second largest number in A using at most 3/2n -2 comparisons.
(i) describe the idea behind your algorithm in English (3 points);
(ii) provide pseudocode (5 points);
(iii) analyze the number of comparisons used in your algorithm (2 points).
1. The main idea behind the algorithm is to scan the array in the linear order and find the maximum element and make the second largest element as the previous value of the maximum value. This basically means that while traversing through the list, we need to compare the current element with the maximum value and if we find a new maximum then we need to make the second-largest value to the previous value of the maximum and update the maximum value.
2. Psuedo-Code
function findFirSecLargest(A):
maximum = -1;
secondmaximum = -1;
for i in A:
if i > maximum:
secondmaximum =
maximum
maximum =
i
print(maximum)
print(secondmaximum)
3. So the total number of comparisons done in the above pseudocode/Algorithm is just n, in which we are comparing each element of the array with the current maximum value.
Friend, That was
a nice question to answer
If you have any doubts in understanding do let me know in the
comment section. I will be happy to help you further.
Thanks