关于 折半查找 while 条件 < , <=

int bin_search(int a[],int len,int key)

{

    int low=0;

int high=len-1;

while(low<=high) //若为low<high; e.g.1,2,3,4,5 如果search 5 ,最终 low==high=4(指的是下标,从0开始。而循环

//体 不执行。

{

 int mid=low+(high-low)/2;

if(a[mid]==key) return mid;

else

if(a[mid]<key)

low=mid+1;

else

high=mid-1;

}

if(low>high) 

return -1;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
折半查找(也称二分查找)需要一个有序数组,先比较数组中间位置的元素和目标元素的大小关系,如果相等则直接返回下标,否则根据大小关系缩小查找范围并继续查找。因此,需要对stu数组进行排序,可以使用STL中的sort函数进行升序排序,然后使用二分查找算法进行查找。 修改后的代码如下: ``` void LookupNum(Student stu[]) { system("cls"); int n = Read(stu); int s; cout << endl << "======>> 查找学生成绩 <<======" << endl; cout << "请输入要查找学生的学号:"; cin >> s; // 先对stu数组按学号升序排序 sort(stu, stu + n, [](const Student& a, const Student& b) { return a.num < b.num; }); // 二分查找目标学号 int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (stu[mid].num == s) { cout << "----------------------------" << endl; cout << "班级:" << stu[mid].class_0 << endl; cout << "学号:" << stu[mid].num << endl; cout << "姓名:" << stu[mid].name << endl; cout << "电子技术:" << stu[mid].elec << endl; cout << "C++程序设计:" << stu[mid].c_program << endl; cout << "多媒体技术:" << stu[mid].media << endl; cout << "大学英语:" << stu[mid].english << endl; cout << "高等数学:" << stu[mid].math << endl; cout << "大学体育:" << stu[mid].sport << endl; cout << "马克思主义基本原理:" << stu[mid].polity << endl; cout << "平均分:" << stu[mid].average << endl; cout << "总分:" << stu[mid].total << endl; return; // 直接返回 } else if (stu[mid].num < s) { left = mid + 1; } else { right = mid - 1; } } cout << "======>> 对不起,无法找到该学生...... <<======" << endl; } ``` 需要注意的是,折半查找要求数组有序,因此在查找之前需要对stu数组按学号升序排序。另外,如果找到目标学生,直接返回即可,不需要继续查找。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值