-5
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

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • 2
    Please read [Under what circumstances may I add "urgent" or other similar phrases to my question, in order to obtain faster answers?](https://meta.stackoverflow.com/q/326569/11082165) – Brian61354270 Feb 23 '23 at 15:55
  • 1
    There are multiple bugs here. First, you should never change `mid` in a given iteration after setting it at the top of the loop. Instead, you need to set `low` or `high`. The assignments to `mid` after the first are dead code, since it is redefined at the top of each loop iteration. Second, you really should use `else if` and `else`. Otherwise you're doing unnecessary work. – Tom Karzes Feb 23 '23 at 15:58
  • Is your input in sorted order? That's a precondition for using binary search. – John Bollinger Feb 23 '23 at 16:06
  • Do apply conventional indentation to your code. That would make it far easier to read, probably even for you, yourself. – John Bollinger Feb 23 '23 at 16:08

1 Answers1

0

wrong:

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

right:

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

mid change is off the table.

Armali
  • 18,255
  • 14
  • 57
  • 171