0

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;

}
1
  • Here is related question link1 and link2 Commented Mar 10, 2014 at 23:33

6 Answers 6

2

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];.

Sign up to request clarification or add additional context in comments.

1 Comment

The only other suggestion I have is to handle null and the empty array. That is if (a == null || a.length == 0) return null;
2

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.

2 Comments

I would start your loop at j = 1, loop until j < a.length, and check if a[j] > max.
actually by adding the if check, you have made the saves a bit of time a bit more expensive than starting at index 0 and using Integer.MIN_VALUE as initial max
1

You need to compare the current element with maximum element, not with the next one.

if (a[j] > max) {
    max = a[j];
}

Comments

1

In Java 8 You can use Stream:

public static int maxArray(int[] a) {
    return Arrays.stream(a).max().getAsInt();
}

Comments

0
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);

4 Comments

Note that this is an int[] and not a T[]. This will not work. Also note that the Object in T extends Object & Comparable<? super T> is redundant.
for redundancy, the declaration of the max function is: public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
I assume you copied this from the source of Collections. It is there for backwards compatibility. There is no reason to have it in your example.
yes, <T extends Comparable> and add a cast to return : (T)
0
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.