Search code examples
ctime-complexitybig-ocomplexity-theory

What should be the time complexity of the given function in terms of Big O?


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.


Solution

  • 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 log1.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