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

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

    Compare in Pairs will work best for minimum comparisons

    # Initialization # 
    - if len(arr) is even, min = min(arr[0], arr[1]), max = max(arr[0], arr[1])
    - if len(arr) is odd, min = min = arr[0], max = arr[0]
    
    # Loop over pairs # 
    - Compare bigger of the element with the max, and smaller with min,
    - if smaller element less than min, update min, similarly with max.
    

    Total Number of comparisons -

    • For size = odd, 3(n - 1) / 2 where n is size of array
    • For size = even, 1 + 3*(n - 2)/2 = 3n/2 - 2

    Below is the python code for the above pseudo-code

    class Solution(object):
        def min_max(self, arr):
            size = len(arr)
            if size == 1:
                return arr[0], arr[0]
    
            if size == 2:
                return arr[0], arr[1]
    
            min_n = None
            max_n = None
            index = None
            if size % 2 == 0:       # One comparison
                min_n = min(arr[0], arr[1])
                max_n = max(arr[0], arr[1])
                st_index = 2
    
            else:
                min_n = arr[0]
                max_n = arr[0]
                st_index = 1
            for index in range(st_index, size, 2):
                if arr[index] < arr[index + 1]:
                    min_n = min(arr[index], min_n)
                    max_n = max(arr[index + 1], max_n)
                else:
                    min_n = min(arr[index + 1], min_n)
                    max_n = max(arr[index], max_n)
    
            return min_n, max_n
    

提交回复
热议问题