Files
data-structures-and-algorithms/homework6/test2.cpp
T
2024-12-22 01:27:31 +08:00

38 lines
1.0 KiB
C++

// 编写一个程序,输出在顺序表(1,2, 3, 4, 5, 6, 7, 8, 9, 10)中采用折半查找方法查找关键字9的过程。
#include<iostream>
#include<vector>
using namespace std;
template <typename T>
int BinarySearch(vector<T> l, T value, int left, int right) {
if (left > right) {
return -1; // 未找到目标值
}
int mid = left + (right - left) / 2; // 计算中间位置
cout << "正在查找第"<<mid+1 <<""<<"其值为"<<l.at(mid)<< endl;
if (l[mid] == value) {
return mid; // 找到目标值,返回索引
} else if (value < l.at(mid)) {
return BinarySearch(l, value, left, mid - 1); // 在左半部分递归查找
} else {
return BinarySearch(l, value, mid + 1, right); // 在右半部分递归查找
}
}
template <typename T>
int BinarySearch(vector<T> l, T value) {
return BinarySearch(l,value, 0, l.size() - 1);
}
int main() {
vector<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int index=BinarySearch(l, 9);
cout<<index<<endl;
return 0;
}