英文:
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<=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;
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论