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

后端 未结 14 1426
深忆病人
深忆病人 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:23

    1. Pick 2 elements(a, b), compare them. (say a > b)
    2. Update min by comparing (min, b)
    3. Update max by comparing (max, a)
    

    This way you would do 3 comparisons for 2 elements, amounting to 3N/2 total comparisons for N elements.

提交回复
热议问题