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 ~
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 -
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