Find the minimum and maximum number in an array

Programming

In this programming tutorial we will find the minimum and maximum element of an array.

Problem statement

Find the minimum and maximum element present in an one dimensional array of integer values. Note the elements of the array can be negative, zero or positive. Also, elements can repeat. Also, there will always be at least 2 elements.

Sample input

[68, 43, 67, 87, 44, 25, 80, 38, 55, -10, 12, 51, 36, 97, 64, 52, 0, 87, -46, 70]

Solution

There are couple of ways we can solve this problem. Lets start with a simple approach.

First, lets pick the first two elements from the input array and find the maximum and minimum.

In the above input, 68 is the maximum and 43 is the minimum.

Now, we loop from the 3rd element onwards, if it exists, till the last element of the array and we compare each element with the current maximum and minimum value and update them accordingly.

So, for example the current minimum value is 43 and current maximum value is 68 and the 3rd element from the input array is 67. So, we compare 67 with 43 and 68. Clearly, 67 is not greater than current maximum and neither it is lesser than the current minimum so we move to the next element in the input array.

The next number is 87 which is clearly greater than the currrent maximum so, we update our maximum to 87.

We continue this process till we reach the end of the array.

Code

Python

numbers = [68, 43, 67, 87, 44, 25, 80, 38, 55, -10, 12, 51, 36, 97, 64, 52, 0, 87, -46, 70]

min_number = numbers[0]
max_number = numbers[1]

if min_number > max_number:
    min_number, max_number = max_number, min_number

for number in numbers[3:]:
    if number < min_number:
        min_number = number
    elif number > max_number:
        max_number = number

assert min_number == -46
assert max_number == 97

print('min', min_number, 'max', max_number)

Output

min -46 max 97

Time complexity

Time complexity for the above solution is O(n).