Reputation: 691
I am trying to find the Minimum and Maximum Value in an ArrayList without Sorting:
Here is my Current Attempt - However I cannot seem to be getting it to work properly:
import java.util.*;
class Untitled {
static ArrayList<Integer> al = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.println(populateArray(al));
System.out.println(findMin(al,0));
}
public static ArrayList<Integer> populateArray(ArrayList<Integer> a) {
al.add(1);
al.add(2);
al.add(30);
al.add(3);
al.add(13);
al.add(34);
al.add(4);
al.add(3);
al.add(2);
al.add(1);
al.add(93);
return a;
}
public static int findMin(ArrayList<Integer> a, int start) {
int min = start;
for(int i=start; i<a.size(); i++) {
if(a.get(i) < a.get(min)) {
min = i;
}
}
return start;
}
}
Upvotes: 0
Views: 2597
Reputation: 13465
You need to do the following::
public static int findMin(ArrayList<Integer> a) {
int min = 0;
for(int i=0; i<a.size(); i++) {
if(i==0) min= a.get(i);
if(a.get(i) < min) {
min = a.get(i);
}
}
return min;
}
public static int findMax(ArrayList<Integer> a) {
int max = 0;
for(int i=0; i<a.size(); i++) {
if(i==0) max= a.get(i);
if(a.get(i) > max) {
max = a.get(i);
}
}
return max;
}
Upvotes: 0
Reputation: 24157
May be you are looking for something like this:
public static void main(String[] args) {
findMinMax(new int[] {10,40,50,20,69,37});
}
public static void findMinMax(int[] array) {
if (array == null || array.length < 1)
return;
int min = array[0];
int max = array[0];
for (int i = 1; i <= array.length - 1; i++) {
if (max < array[i]) {
max = array[i];
}
if (min > array[i]) {
min = array[i];
}
}
System.out.println("min: " + min + "\nmax: " + max);
}
Obviously this is not going to one of the most optimized solution but it will work for you. It uses simple comparison to track min
and max
values. Output is:
min: 10
max: 69
Upvotes: 0
Reputation: 100169
Using Java 8 you can do this very easily traversing the list only once:
IntSummaryStatistics stats = al.stream().mapToInt(Integer::intValue).summaryStatistics();
System.out.println("Minimum is: "+stats.getMin());
System.out.println("Maximum is: "+stats.getMax());
Upvotes: 2