# I wrote a O(log N) code for largest element in an array today but is this an already existing way to find max element in an array? [closed]

Largest element in an array's most optimal approach. The code I have written has passed all test cases in https://www.naukri.com/code360/problems/largest-element-in-the-array-largest-element-in-the-array_5026279, and it computes in O(logN) time. Are there any mistakes here? And I cannot find any solutions that exists in LogN time computation. Is there any edge cases to this?

static int largestElement(int[] arr, int n) {
int max = arr[0];
int i = 1;
int j = n-1;
while(i<=j){
if(arr[i]>=max  && arr[i] >= arr[j]) max = arr[i];
else if(arr[j]>=max  && arr[j] >= arr[i]) max = arr[j];
i++;
j--;
}
return max;
}

• Java? C#? Something else? Commented Apr 18 at 12:24
• This isn't O(log(n)). It is O(n). Commented Apr 18 at 12:44

# linear algorithm

The OP code does not complete in $$\O(\log n)\$$ logarithmic time.

In general a correct algorithm will have at least $$\O(n)\$$ linear complexity. It cannot do better than that, since the maximum element could be hiding at any position.

# code

This line of source code is correct:

    int max = arr[0];


In particular, initializing in this way is better than using a $$\- \infty\$$ sentinel such as $$\-(2^{63})\$$.

The remainder of the code should be rewritten, as a short loop.

(When initially reading it, I was kind of hoping that assignment would immediately produce the answer in $$\O(1)\$$ constant time by virtue of input being in monotonic decreasing sorted order, but then I saw the problem puts no constraint on the input vector.)

        if(arr[i]>=max  && arr[i] >= arr[j]) max = arr[i];

Please don't do that. Surround if / else statements with { } braces, even if there's only a single statement as we see here.