views:

118

answers:

1

http://en.wikipedia.org/wiki/Binary_search_algorithm#Average_performance

BinarySearch(int A[], int value, int low, int high)
{
    int mid;
    if (high < low)
        return -1;
    mid = (low + high) / 2;
    if (A[mid] > value)
        return BinarySearch(A, value, low, mid-1);
    else if (A[mid] < value)
        return BinarySearch(A, value, mid+1, high);
    else
        return mid;
}

If the integer I'm trying to find is always in the array, can anyone help me write a program that can calculate the average performance of binary search algorithm?

edit: I know I can do this by actually running the program and counting the number of calls, but what I'm trying to do here is to do it without calling the function.

edit2: KennyTM: That is a time complexity, I'm trying to calculate the average number of calls. For example, the average number of calls to find a integer in A[2], it would be 1.67 (5/3)

A: 

You don't need a "program". You can just count the number of calls to the BinarySearch method.

You can do that easily by passing another parameter (by pointer) or using a global variable. In this case - it's a toy - so I'd probably go quick and dirty with the global.

Stephen
It's 2. What do I win?
Jurily
@Jurily: hehe, no link to instantrimshot.com? :)
Stephen