Find the min and max number from the given unsorted array
Solution)
Using a pair (min and max), we can just compare two elements step by step. Then, compare the smaller one with the current min value and the bigger one with the current max value. In this solution, we are assuming that the value is integer.
class Pair {
int min;
int max;
}
public Pair findMinMax(int[] arr) {
Pair pair = new Pair();
// if the size of the given array is odd, assign the first element to both min and max, otherwise,
// compare the first and second element, and then, assign min and max
if (arr.length%2 == 0) {
if (arr[0] > arr[1]) {
pari.min = arr[1];
pari.max = arr[0];
} else {
pair.min = arr[0];
pair.max = arr[1];
}
} else {
pair.min = arr[0];
pair.max = arr[0];
}
for (int i = 2; i < arr.length-1; i += 2) {
if (arr[i] > arr[i+1]) {
pair.min = Math.min(pair.min, arr[i+1]);
pair.max = Math.max(pair.max, arr[i]);
else {
pair.min = Math.min(pair.min, arr[i]);
pair.max = Math.max(pair.max, arr[i+1]);
}
}
return pair;
}