An array of numbers is given, where is an even number. The maximum as well as the minimum of these numbers needs to be determined. Which of the following is TRUE about the number of comparisons needed?
View worked solution
Answer: B
To find both the maximum and minimum elements in an array of numbers (where is even), we can use an optimal pairwise comparison algorithm to minimize the number of comparisons:
- Initialize: Compare the first two elements of the array. Assign the larger element to
maxand the smaller element tomin.
This requires comparison. - Process Remaining Elements: Group the remaining elements into pairs. There will be pairs. For each pair:
- Compare the two elements of the pair with each other to find the local maximum and local minimum ( comparison).
- Compare the local maximum with the global
max( comparison). - Compare the local minimum with the global
min( comparison).
Summing these up, the total number of comparisons is:
Since we can achieve this with exactly comparisons, it is true that at most comparisons are needed.
Free practice · Your answers on this page are not saved.
