Finding the maximum and minimum in array using minimum numbers of comparison in java

Finding the maximum and minimum in array using minimum numbers of comparison in java

Table of contents

No heading

No headings in the article.

Problem statement:- Given an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons.

For solving any problems, I would divide it into the following part

Given: Array,

Finding: Max number, Min number,

Condition: Minimum comparison,

Output: two number one is max and one is minimum

So here seeing the output structure, it's very clear that we have to return two numbers at a time so the option for us is to use an array or pair ...using an array would be costly here because at max we know we have only two elements to return so we can go with pair.

Now here comes the main part of the problem how we can achieve our desired result. From seeing problem statements, I can predict that I have to traverse the whole array and while traversing I can go with comparing each element with min_value and max_value(We will target first two elements and compare them separately to store our first values of min and max). At the end of the array, we will be having minimum number and a maximum stored in our min_value and max_value.

Below the program for the above problem statement:


public class ReverseArray {

    static class Pair {
        int min;
        int max;
    }

    static Pair getMinMax(int[] arr, int n) {
        Pair minmax = new Pair();
        if (n == 1) {
            minmax.min = arr[0];
            minmax.max = arr[0];
            return minmax;
        }
        if (arr[0] > arr[1]) {
            minmax.max = arr[0];
            minmax.min = arr[1];
        } else {
            minmax.max = arr[1];
            minmax.min = arr[0];
        }
        for (int i = 2; i < arr.length; i++) {
            if (arr[i] > minmax.max) {
                minmax.max = arr[i];
            } else if (arr[i] < minmax.max) {
                minmax.min = arr[i];
            }
        }
        return minmax;
    }

    public static void main(String args[]) {
        int arr[] = { 1000, 300, 5000, 40, 39000 };
        int n = 5;
        Pair minmax = getMinMax(arr, n);

        System.out.println("\nMaximum value the comes in array is:" + minmax.max);
        System.out.println("\nMaximum value the comes in array is:" + minmax.min);
    }
}