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

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

first occurrence code binary search debug in c

问题

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

  1. int firstOcc(int a[], int m, int x)
  2. {
  3. int high = m - 1, low = 0, mid, index = -1;
  4. while (low <= high)
  5. {
  6. mid = (low + high) / 2;
  7. if (a[mid] < x)
  8. {
  9. mid = low + 1;
  10. }
  11. if (a[mid] > x)
  12. {
  13. mid = high - 1;
  14. }
  15. if (a[mid] == x)
  16. {
  17. index = mid;
  18. high = mid - 1;
  19. }
  20. }
  21. return index;
  22. }

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

英文:
  1. int firstOcc(int a[],int m,int x)
  2. {
  3. int high=m-1,low=0,mid,index=-1;
  4. while(low&lt;=high){
  5. mid=(low+high)/2;
  6. if(a[mid]&lt;x){
  7. mid=low+1;}
  8. if(a[mid]&gt;x){
  9. mid=high-1;}
  10. if(a[mid]==x){
  11. index=mid;
  12. high=mid-1;}
  13. }
  14. return index;
  15. }

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

对的:

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

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

英文:

wrong:

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

right:

  1. low=mid+1;}
  2. 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:

确定