- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
There are several methods to find a minimum and maximum method. However, this program uses the divide and conquer method.
Program :
class ArrayMethod{
Number getMinMax(int arr[], int low, int high) {
Number minmax = new Number();
Number mml = new Number();
Number mmr = new Number();
int mid;
System.out.println("Start Index:"+low+ " "+ "End Index:"+high);
// If there is only one element
if (low == high) {
minmax.max = arr[low];
minmax.min = arr[low];
return minmax;
}
/* If there are two elements */
if (high == low + 1) {
if (arr[low] > arr[high]) {
minmax.max = arr[low];
minmax.min = arr[high];
} else {
minmax.max = arr[high];
minmax.min = arr[low];
}
return minmax;
}
/* If there are more than 2 elements */
mid = (low + high) / 2;
mml = getMinMax(arr, low, mid);
mmr = getMinMax(arr, mid + 1, high);
// System.out.println("Max l : Index:"+mml.max+ " "+ "Min l: Index:"+ mml.min);
// System.out.println("Max r : Index:"mmr.max+ " "+ "Min r: Index:"+ mmr.min);
/* compare minimums of two parts*/
if (mml.min < mmr.min) {
minmax.min = mml.min;
} else {
minmax.min = mmr.min;
}
/* compare maximums of two parts*/
if (mml.max > mmr.max) {
minmax.max = mml.max;
} else {
minmax.max = mmr.max;
}
return minmax;
}
public static void main(String[] args) {
int a[] = {6,7,3,2,4,5,10};
//use divide and quere method to find a max and min number from the array
ArrayMethod array = new ArrayMethod();
Number value =array.getMinMax(a,0,a.length-1);
System.out.println(value.min + "" + value.max);
}
}
class Number {
public int min =0;
public int max =0;
}
- Get link
- X
- Other Apps
Comments
Post a Comment
Any Query Regarding Article Ask me in comment