编写代码实现现在某个学院有20名同学分属于2个班级(Class1 和Class2,每个班有10名同学,每个同学记录包括:班级、学号、姓名、性别、电话号码等信息)。 3.以学号为主关键字,以班级为次关键字,建立一个顺序表,表中的每个数据元素是一个记录,其中的某个域用来存储关键字的值,按关键字的值进行顺序查找。为分析排序方法的稳定性,关键字可用次关键字。 4.完成如下函数创建函数,查找函数,摧毁函数和遍历函数(其中查找函数用顺序查询和折半查询两种方式实现)
时间: 2024-03-03 11:51:53 浏览: 19
以下是 C++ 代码实现:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
const int MAXSIZE = 20;
struct Student {
string class_name;
int id;
string name;
char gender;
string phone;
};
struct SeqList {
Student data[MAXSIZE];
int length;
};
bool cmp(const Student& a, const Student& b) {
if (a.class_name == b.class_name) {
return a.id < b.id;
}
return a.class_name < b.class_name;
}
void create(SeqList& list) {
list.length = 0;
for (int i = 0; i < 10; i++) {
Student s;
s.class_name = "Class1";
s.id = i + 1;
s.name = "Student" + to_string(s.id);
s.gender = 'M';
s.phone = "123456789";
list.data[list.length++] = s;
}
for (int i = 0; i < 10; i++) {
Student s;
s.class_name = "Class2";
s.id = i + 1;
s.name = "Student" + to_string(s.id);
s.gender = 'F';
s.phone = "987654321";
list.data[list.length++] = s;
}
sort(list.data, list.data + list.length, cmp);
}
int search_seq(SeqList& list, int id) {
for (int i = 0; i < list.length; i++) {
if (list.data[i].id == id) {
return i;
}
}
return -1;
}
int search_bin(SeqList& list, int id) {
int left = 0, right = list.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (list.data[mid].id == id) {
return mid;
} else if (list.data[mid].id > id) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
void destroy(SeqList& list) {
list.length = 0;
}
void traverse(SeqList& list) {
for (int i = 0; i < list.length; i++) {
cout << "Class: " << list.data[i].class_name
<< ", ID: " << list.data[i].id
<< ", Name: " << list.data[i].name
<< ", Gender: " << list.data[i].gender
<< ", Phone: " << list.data[i].phone << endl;
}
}
int main() {
SeqList list;
create(list);
traverse(list);
int id = 5;
int index_seq = search_seq(list, id);
int index_bin = search_bin(list, id);
if (index_seq == -1) {
cout << "Not found (sequential search)" << endl;
} else {
cout << "Found (sequential search): " << index_seq << endl;
}
if (index_bin == -1) {
cout << "Not found (binary search)" << endl;
} else {
cout << "Found (binary search): " << index_bin << endl;
}
destroy(list);
return 0;
}
```
这个程序实现了创建一个顺序表,包含 20 名学生的信息,通过学号和班级进行排序。然后实现了两种查找函数,分别是顺序查找和折半查找。最后实现了摧毁函数和遍历函数。你可以按照自己的需要修改和调整这个程序。