简体   繁体   English

计算两个数组中元素的二进制搜索逻辑(GFG)

[英]Binary search logic for Counting elements in two arrays(GFG)

I am using this logic to find the element which is less than or equal to x in a sorted array b[].我正在使用此逻辑在排序数组 b[] 中查找小于或等于 x 的元素。 However, its not working for some of the testcase.但是,它不适用于某些测试用例。

int binary_search(int x, int b[], int b_size)
{
    int low = 0;
    int high = b_size-1;
    
    
    while(low<=high)
    {
        int mid = low + (high-low)/2;
        
        if(b[mid]<=x && b[mid+1]>x) return mid;
        else if(b[mid]>x) high = mid-1;
        else low = mid+1;
    }
}

After looking for a soln, I found the below logic.在寻找解决方案后,我发现了以下逻辑。 Can someone please tell me what's the difference between my logic and this one?有人可以告诉我我的逻辑和这个逻辑有什么区别吗?

int binary_search(int arr[], int l, int h, int x)
{
    while (l <= h) {
        int mid = (l + h) / 2;
 
        // if 'x' is greater than or equal to arr[mid],
        // then search in arr[mid+1...h]
        if (arr[mid] <= x)
            l = mid + 1;
 
        // else search in arr[l...mid-1]
        else
            h = mid - 1;
    }
 
    // required index
    return h;
}

In your code you are not considering that mid+1 can be equal to b_size, suppose b_size=1 then mid=0 and mid+1=1, it means you are checking for a value at index 1 ie b[1] that is out of bound for array b.在您的代码中,您没有考虑 mid+1 可以等于 b_size,假设 b_size=1 然后 mid=0 和 mid+1=1,这意味着您正在检查索引 1 处的值,即 b[1]数组 b 越界。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM