int find_peak (int n, int A []) {
int left, right, lmid, rmid;
left = 0;
right = n - 1;
while (left + 3 <= right) {
lmid = (2 * left + right) / 3;
rmid = (left + 2 * right) / 3;
if (A[lmid] <= A[rmid])
left = lmid;
else
right = rmid;
}
int x = left;
for (int i = left + 1; i <= right; i ++)
if (A[i] > A[x])
x = i;
return A[x];
}
I was trying to solve this function for its BigO notation, but I am very confused about it. Is it O(log n) or something else? I can somewhat solve it in my head but I can't do it on properly.
Yes, the loop is cut roughly in half at each iteration
lmid = (2 * left + right) / 3;
rmid = (left + 2 * right) / 3;
if (A[lmid] <= A[rmid])
left = lmid;
else
right = rmid;
To be precise it's log 1.5 (n) , because the actual length right-left
decreases only by 1 / 3 , not halving the iterations. The complexity is still O(log(n))
You can try it here https://onlinegdb.com/rkI5gn3Xd
Thanks to chqrlie for prompting me to give a more detailed answer
The complexity of the above code should be O(log3n) ie.. logn base 3 . because in the while loop the value of rmid
always comes out as greater than lmid
.So, for a given value of right ie.. n
, the value of left will be reduced by a multiple of 1/3 at each iteration.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.