Java – Is This Code Efficient for Finding Array Max?

java

I am trying to find max value of an array, firstly i am shorting my array min to max after that i am using array[array.length-1] Is this logic efficient in large arrays?

public static int findMax(int[] array){

    Arrays.sort(array);

    int max = array[array.length-1];

    return max;
}//end method

Best Answer

No it's not.

Arrays.sort(array);

That line alone has an O(nlogn) running time. It can result in as many iterations as n, where n is the number of elements in the array, multiplied by log base 2 of n.

It would be much faster to just iterate through the array once.

public static int findMax(int[] array) {
    int indexOfMax = 0;
    for (i=1; i < array.length; i++) {
        if (array[i] > array[indexOfMax] {
            indexOfMax = i;
    }
    return indexOfMax
}

That has a maximum running time as O(n).