Search code examples
cbinary-search

Why does my binary search always return -1


I'm quite new to recursive function and is trying to search an id in a struct array, why does it always return -1 instead of 3?

This is the struct

struct Student{
  int id;
};

struct Student student[4];

My binary search function

int binary(int start, int end, int search){
  if(end >= start){
    int mid = (start + (end - start)) / 2;

    if(student[mid].id == search){
      return mid;
    }

    if(search > student[mid].id){
      return binary(mid+1, end, search);
    }
    else{
      return binary(1, mid-1, search);
    }
  }
  else{
    return -1;
  }

The main function

int main(){
  student[0].id = 1004;
  student[1].id = 1003;
  student[2].id = 1002;
  student[3].id = 1001;

  int position = binary(0, 3, 1001);

  printf("The search value 1001 is at index number %d", position);
}
```

Solution

  • Because you have to order the element in ascending order, not descending, so it should be:

      student[0].id = 1001;
      student[1].id = 1002;
      student[2].id = 1003;
      student[3].id = 1004;
    

    or you have to change the < with a > on binary function like

    int binary(int start, int end, int search){
      if(end >= start){
        int mid = (start + end) / 2;
    
        if(student[mid].id == search){
          return mid;
        }
    
        if(search < student[mid].id){
          return binary(start, mid-1, search);
        }
        else{
          return binary( mid+1, end,  search);
        }
      }
      else{
        return -1;
      }
    }
    

    also the index of the recursive call was wrong