Reputation: 105
Ok so I'm trying to find the largest element in an array, and I realize this is not the best method to do this, it only works in some cases. Would appreciate some pointers on how to change my code so it works for all instances.
public static int maxArray(int[] a) {
int max = 0;
for (int j = 0; j < a.length-1; j++) {
if (a[j+1] > a[j]) {
max = a[j+1];
} else {
max = a[j];
}
}
return max;
}
Upvotes: 0
Views: 2232
Reputation: 11
In Java 8 You can use Stream:
public static int maxArray(int[] a) {
return Arrays.stream(a).max().getAsInt();
}
Upvotes: 1
Reputation: 111
public static int getMaxElement(int[] elements) {
int max = elements[0];
for (int j = 0; j < elements.length-1; j++) {
if (elements[j] > max) {
max = elements[j];
}
}
return max;
}
Upvotes: 0
Reputation: 3320
Use this method.
public static int maxArray(int[] a) {
int max = a[0]; // saves a bit of time
for (int j = 1; j < a.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
return max;
}
This is pretty speedy and concise.
Upvotes: 2
Reputation: 23
public static <T extends Object & Comparable<? super T>> T maxArray(T[] array) {
return Collections.max(Arrays.asList(array));
}
after you make calls to the function, eg:
Integer[] a = { 1, 5, -6, 3, 0, 2 };
Integer max = maxArray(a);
System.out.println(max);
Upvotes: 0
Reputation: 201409
I suggest you do it like so,
Start with max = a[0];
then loop with j
from 1
to a.length
.
Compare a[j]
to max
, that is if a[j] > max
then set max = a[j];
.
Upvotes: 2
Reputation: 2826
You need to compare the current element with maximum element, not with the next one.
if (a[j] > max) {
max = a[j];
}
Upvotes: 1