In: Computer Science
Write an algorithm that finds both the smallest and largest numbers in a list of n numbers. Try to find a method that does at most 1.5n comparisons of array items.(but please code in java).
public class MinMax {
public static void main(String[] args) {
int arr[]= {10,5,4,12,15,24,29,32,9,19};
int minmax[]=getMinMax(arr);
System.out.println("Min: "+minmax[0]);
System.out.println("Max: "+minmax[1]);
}
// here this single methods returns array of values
// 1st index will have min value and 2nd index will have the max value
private static int[] getMinMax(int[] arr) {
int res[]=new int[2];
int min=arr[0];
int max=arr[0];
// iterating through array to find min and max values in the array
for(int i=0;i<arr.length;i++) {
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
}
res[0]=min;
res[1]=max;
return res;
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
Please Like and Support me as it helps me a lot