开发者

Average performance of binary search algorithm?

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? 开发者_如何学Python

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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜