我对递归函数还很陌生,正在尝试在结构数组中搜索id,为什么它总是返回-1而不是3?
这是结构
struct Student{
int id;
};
struct Student student[4];
我的二进制搜索功能
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;
}
主要功能
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);
}
```
答案 0 :(得分:4)
因为您必须按升序而不是降序对元素进行排序,所以它应该是:
student[0].id = 1001;
student[1].id = 1002;
student[2].id = 1003;
student[3].id = 1004;
或者您必须将<
更改为>
,例如二进制函数
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;
}
}
递归调用的索引也是错误的