首次出现的二分查找调试在C中的代码

huangapple go评论65阅读模式
英文:

first occurrence code binary search debug in c

问题

以下是代码部分的中文翻译:

int firstOcc(int a[], int m, int x)
{
    int high = m - 1, low = 0, mid, index = -1;

    while (low <= high)
    {
        mid = (low + high) / 2;

        if (a[mid] < x)
        {
            mid = low + 1;
        }

        if (a[mid] > x)
        {
            mid = high - 1;
        }

        if (a[mid] == x)
        {
            index = mid;
            high = mid - 1;
        }
    }

    return index;
}

请注意,代码中有一些问题,可能会导致功能不正常。如果您希望了解问题所在,可以提供更多上下文或详细信息,以便进行进一步的分析。

英文:
int firstOcc(int a[],int m,int x)
{
    int high=m-1,low=0,mid,index=-1;

    while(low&lt;=high){
    mid=(low+high)/2;

    if(a[mid]&lt;x){
        mid=low+1;}

    if(a[mid]&gt;x){
        mid=high-1;}

    if(a[mid]==x){
        index=mid;
        high=mid-1;}
    }

    return index;
}  

why is my function isn't working ?! finding first occurrence. what is wrong with it ?

can't find the bug, copied almost identical code from the internet it worked but I need to know why my code isn't working

答案1

得分: 0

对的:

        low=mid+1;}
        high=mid-1;}

mid 的更改不在讨论范围内。

英文:

wrong:

        mid=low+1;}
…
        mid=high-1;}

right:

        low=mid+1;}
…
        high=mid-1;}

mid change is off the table.

huangapple
  • 本文由 发表于 2023年2月23日 23:51:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定