二进制搜索 - 延迟平等检查

时间:2016-02-26 04:46:16

标签: c

http://ideone.com/RT84T6

while (first <= last) {
    // Assert: Array is sorted and first <= last
    //Initialization:target is within (extremes inclusive) the range of first     and last. IE First<=x<=Last
    mid = (first + last) / 2;

    //Maintenance: Increasing first to mid+1 if x>mid or decrease last to     min-1 if x<mid.
    if (target < arr[mid])
        last = mid - 1;
    else
        first = mid + 1;
}

//Termination: target is not within the array.
return -1;

if ((first <= target) && (arr[first]==target))
    return 1;
else
    return -1;

每次运行二分查找时,我得到-1的输出(延迟检测相等版本)。

我无法弄清楚它产生的结果是-1。

1 个答案:

答案 0 :(得分:0)

这是一个完整的解决方案,包括一个简单的测试驱动程序:

#include <stdio.h>

//
// Returns the array index if target is present.
// Returns -1 if target is absent.
//
int bin_search(int *arr, int len, int target)
{
    int first = 0;
    int last = len - 1;
    int mid;

    while (first < last) {
        mid = (first + last) / 2;
        // Note:  We require mid < last  for this to work.  This should be
        // the case since integer division uses "truncation towards zero".

        if (arr[mid] < target) {
            first = mid + 1;
        }
        else {
            last = mid;
        }
    }

    if (first == last && arr[first] == target) {
        return first;
    }

    return -1;
}

int main()
{
    static int a[5] = {1, 2, 3, 4, 5};
    int ix;
    int i;

    for (i = 0; i <= 6; i++) {
        ix = bin_search(a, 5, i);
        printf("%d: %d\n", i, ix);
    }

    return 0;
}

输出结果为:

0: -1
1: 0
2: 1
3: 2
4: 3
5: 4
6: -1

请注意,在我找到last的情况下,我反转了环路测试,以便first更新而不是target。这可以保证last在这种情况下减少。也可以使原件工作,但是在设置中间而不是下降时需要除以2。

我还更改了bin_search以返回目标索引(如果存在),如果不存在则返回-1。