tags:

views:

559

answers:

3

Below is a binary search function.

int search(int a[], int v, int left, int right)
{
    while (right >= left)
    {
        int m = (left + right)/2;
        if (v == a[m]) 
            return m;
        if (v < a[m])
            right = m - 1;
        else left = m + 1;
    }
    return -1;
}

How do I determine the Big-O notation for this function?

Is this search function O(n) since the while loop is dependent on the value of left?

+11  A: 

In each step, the range of values halves (roughly) - if you start with right - left == 100, then at the second step it will be 49, then 24, then 11 etc.

Assuming n = right - left, the complexity is O(log n). (It's dependent on the values of both right and left.)

Jon Skeet
If this wasn't you would it have been accepted so quickly?
ChaosPandion
Given the question starts 'This is a binary search...', unless the code is badly messed up, the answer is a no brainer. Rightly accepted, IMO.
Shane MacLaughlin
@Shane - Well clearly this person is learning about the notation. How does he know it is correct?
ChaosPandion
He justifies the answer with logic.That being said, homework questions leave one with a bad taste.
Xorlev
+6  A: 

Jon Skeet already answered the question.

Here I show how we can solve it mathematically.

Since in each loop we halve the range, in the worst case we'll need steps iterations at most.
How do we calculate the steps number?

"Halving the range" can be expressed as: range / 2steps

We can continue halving until range becomes 1.
So the equation is: range / 2steps = 1

Solution:
lg(range / 2steps) = lg(1)
lg(range) - steps*lg(2) = 0

steps = lg(range), where lg is the logarithm with base 2.

Nick D
A: 

BIG-OH IS 0(Lgn)

mubashir