void LookupNum(Student stu[]) { system("cls"); int n = Read(stu); int s; int i = 0; cout << endl << "======>> 查找学生成绩 <<======" << endl; cout << "请输入要查找学生的学号:"; cin >> s; while ((stu[i].num - s) != 0 && i < n)i++; if (i == n) { cout << "======>> 对不起,无法找到该学生...... <<======" << endl; } else { cout << "----------------------------" << endl; cout << "班级:" << stu[i].class_0 << endl; cout << "学号:" << stu[i].num << endl; cout << "姓名:" << stu[i].name << endl; cout << "电子技术:" << stu[i].elec << endl; cout << "C++程序设计:" << stu[i].c_program << endl; cout << "多媒体技术:" << stu[i].media << endl; cout << "大学英语:" << stu[i].english << endl; cout << "高等数学:" << stu[i].math << endl; cout << "大学体育:" << stu[i].sport << endl; cout << "马克思主义基本原理:" << stu[i].polity << endl; cout << "平均分:" << stu[i].average << endl; cout << "总分:" << stu[i].total << endl; } }修改为折半查找
时间: 2023-08-20 19:42:48 浏览: 123
void StatisticAnalysis(STU stu[], int n, int m).vsdx
折半查找(也称二分查找)需要一个有序数组,先比较数组中间位置的元素和目标元素的大小关系,如果相等则直接返回下标,否则根据大小关系缩小查找范围并继续查找。因此,需要对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数组按学号升序排序。另外,如果找到目标学生,直接返回即可,不需要继续查找。
阅读全文