0

The following is my own set-up code:

Search_and_Sum(key, A,n)    A[1..n]
    int sum = 0;
    for(int i=0; i<=n+n+1000; i++){
        for(int j=A.length; j>=1; j/=2){
            if(key==A[j]) break;
            else          sum+=j;
        }
    }
    return sum;

Well, I think the first loop has time complexity $O(n)$ and the inner loop has time complexity $O(log\ n)$, so in the worst case, the running time is $O(n\ log\ n)$.

But, I can't figure out how to find the running time in the best case. Any ideas?

Edit:

Is this is an equivalent formulation of the code with the same running time?

Search_and_Sum(key, A,n)    A[1..n]
    int sum = 0;
    int k = A.length;
    while(k>=1 && key!=A[k]){
        sum=*key;
        k/=2;
        }
    }
    return sum;
Raphael
  • 72,336
  • 29
  • 179
  • 389
  • 1
    Are you sure the code is correct? The inner loop doesn't depend on i at all, so the code is just "Do this $2n+1000$ times." Since the inner loop doesn't depend on i, the best case occurs just when the last element of A is key. – David Richerby Mar 06 '15 at 01:10
  • Well, I intentionally decided to make the inner loop independent of i. I can now see how the best case becomes $\Omega(n)$ because in the best case, the inner loop just runs a single time. – hello.mellower Mar 06 '15 at 01:23
  • I've been trying to rewrite the code using a while loop. Can you please check if my following edit is an equivalent formulation? – hello.mellower Mar 06 '15 at 01:24
  • 1
  • Be wary of your formulation. The "first loop" does not have "complexity" $O(n)$; it includes the second, inner loop, so it has the total "complexity". Think in terms of "how many iterations?". See our reference question on how to translate your code to mathematics; the best-case input is for you to determine (but mathematics can guide you: what A minimizes the expression?). See also [tag:runtime-analysis+loops].
  • – Raphael Mar 06 '15 at 06:50