## Thursday, June 23, 2022

### Java Program to Find Maximum And Minimum Values in an Array

To find maximum and minimum values in an array in Java you can use one of the following options-

1. Iterate the array and look for the maximum and minimum values. See example.
2. You can also write a recursive method to recursively go through the array to find maximum and minimum values in an array. See example.
3. You can use Arrays.sort() method to sort the array and then take the first and last elements of that sorted array. See example.

### Iterating array to find largest and smallest values

Start by having two variables (max and min) with initial value as the first element of the array. Iterate through the array and compare current element with max variable, if current array element is greater than the max then assign the current element to max. Otherwise compare element with min variable, if current array element is less than the min then assign the current element to min.

```public class MaxMinArray {
public static void main(String[] args) {
int arr[] = {54, 24, -4, 0, 2, 45, 54, -9, 7};
// assign first array element to two variables
int max = arr;
int min = arr;
// iterate and compare from array index 1
for(int i = 1; i < arr.length; i++){
if(max < arr[i]){
max = arr[i];
}else if(min > arr[i]){
min = arr[i];
}
}
System.out.println("Maximum number = "
+ max + " Minimum number = " + min);
}
}```
Output
`Maximum number = 54 Minimum number = -9`

### Find maximum and minimum values in array using recursion

```public class MaxMinArray {
public static void main(String[] args) {
int arr[] = {54, 24, 4, 0, 2, 45, 55, 9, -7, 68};
int max = maxUsingRecursion(arr, arr, 0);
int min = minUsingRecursion(arr, arr, 0);
System.out.println("Maximum number = "
+ max + " Minimum number = " + min);
}

private static int maxUsingRecursion(int[] arr, int num, int size){
// base case
if(size == arr.length){
return arr[size-1];
}
return Math.max(num, maxUsingRecursion(arr, arr[size], ++size));
}

private static int minUsingRecursion(int[] arr, int num, int size){
// base case
if(size == arr.length)
return arr[size-1];
return Math.min(num, minUsingRecursion(arr, arr[size], ++size));
}
}```
Output
`Maximum number = 68 Minimum number = -7`

### Find maximum and minimum values in array by sorting

```public class MaxMinArray {
public static void main(String[] args) {
int arr[] = {54, 24, 4, 0, 2, 45, 55, 9, -7, 68};
Arrays.sort(arr);

System.out.println("Maximum number = "
+ arr[arr.length - 1] + " Minimum number = " + arr);
}
}```
Output
`Maximum number = 68 Minimum number = -7`

That's all for the topic Java Program to Find Maximum And Minimum Values in an Array. If something is missing or you have something to share about the topic please write a comment.

You may also like