折半查询

“”"
0 1 2 3 4 5 6 7 8 9
list = [11,22,33,44,55,66,77,88,99,111]
假设需要:66
第一次:(0 + 9)//2 = 4 ;55 和 66比较,
接下来在55的右边找:66,77,88,99,111
第二次:(5+9)//2 = 7 88和 66
接下来在88的左边找:66,77
第三次:(5+6)//2 = 5 66 == 66,对应下标5

开始下标:0开始 慢慢变大
结尾下标:(个数-1) 慢慢减小

“”"

list = [11,22,33,44,55,66,77,88,99,111]
n = int(input(“输入需要查找的值:”))
start=0#最左边开始的下标
end=len(list)-1 #最右边开始的下标
index=-1 #n 对应的下标 -1 没有找到
while start<=end:
#中间值 与 n比较
mid=(start+end)//2
if list[mid]==n: #找到
index=mid
break
elif list[mid]<n: #继续 在中键值右边找
start=mid +1
else:end=mid-1
print("%d对应的下标 %d"%(n,index))

以下是 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 名学生的信息,通过学号和班级进行排序。然后实现了两种查找函数,分别是顺序查找和折半查找。最后实现了摧毁函数和遍历函数。你可以按照自己的需要修改和调整这个程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值