views:

238

answers:

7
procedure max (a[1..n]: integers)
    max := a[1]
    for i := 2 to n
        if max < a[i] then max := a[i]

Is the complexity O(1) or O(n) with the best case scenario? The sequence contains n elements. It is pseudocode.

+2  A: 

O(n) - you have to scan n elements, or a factor of n (n/2, n/4 etc) - still O(n).

Traveling Tech Guy
+7  A: 

There's no difference between the best case and worst case asymptotic running times for this algorithm. In all cases, you have to traverse the whole array (n elements) and your algorithm would be O(n).

Theoretically, there's no way you can find the maximum element of an arbitrary array in less than O(n) since you should always visit each element at least once.

Mehrdad Afshari
There's no way to improve on O(n) *using conventional hardware*.
Artelius
Artelius: We're usually talking about the Random Access Machine model by default. Of course, the running time can be different when you switch to other computational models.
Mehrdad Afshari
@Mehrdad: I know, I was being cheeky. A bit annoyed that I haven't been upvoted despite describing some bugs in the code.
Artelius
+4  A: 

The algorithm is O(n) in the best case, average case, and worst case. It also doesn't work, since it only refers to a1 and uses < where it should use >.

Artelius
You're right, so I fixed it. But I think the use of < was correct since it's "if max < a[i] max := a[i]".
paxdiablo
Upvoting to smooth over Artelius' hurt feelings :-)
paxdiablo
Oh. Yes. I really should stay away from SO during the exam period.
Artelius
Thanks paxdiablo. You're all right :)
Artelius
A: 

If you have code that reads:

for i := 2 to n

Then that code will be O(n) best case.

I'm curious why you think it might be constant time?

Moishe
+2  A: 

Roughly, O(1) means that whatever the size of the input, you can implement the solution in fixed number of steps.

O(n) means that if you have n inputs, the solution will be implemented in An steps (where A is a number, not another variable). Clearly, if you have for loop which counts from 2 to n, that is n cycles, meaning that if you have An input elements, your loop will count from 2 to An, meaning that it is on the same level az the input, so it's O(n). But that's how linear scanning is. :)

Tamás Mezei
A: 

You have to traverse the whole array. So the complexity would be O(n).

Ritz
A: 

O(n)

you can achieve the O(1) if the array was sorted, so you'll just return the last element.

but in random arranged elements the best order for this problem is O(n)

Ali El-sayed Ali