简体   繁体   English

为什么我的二分查找总是返回 -1

[英]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?我对递归 function 很陌生,并且正在尝试在结构数组中搜索 id,为什么它总是返回 -1 而不是 3?

This is the struct这是结构

struct Student{
  int id;
};

struct Student student[4];

My binary search function我的二进制搜索 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主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);
}
```

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或者您必须在二进制 function 上更改<>

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递归调用的索引也是错误的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM