How to find max. and min. in array using minimum comparisons?

后端 未结 14 1475
深忆病人
深忆病人 2020-12-04 09:08

This is a interview question: given an array of integers find the max. and min. using minimum comparisons.

Obviously, I can loop over the array twice and use ~

14条回答
  •  执念已碎
    2020-12-04 09:39

    go for divide and conquer !

    1,3,2,5

    for this finding min,max will take 6 comparisons

    but divide them

    1,3 ---> will give min 1 and max 3 in one comparison
    2,5 ---> will give min 2 and max 5 in one comparison 
    

    now we can compare two mins and maxs

    min(1,2) --> will give the final min as 1 (one comparison)
    max(3,5) ---> will give the final max as 5 (one comparison)
    

    so totally four comparisons to find both min and max.

提交回复
热议问题