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

38 lines
1.1 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(const vector<T>& arr, T target, int left, int right) {
if (left > right) {
return -1; // 未找到目标值
}
int mid = left + (right - left) / 2; // 计算中间位置
cout << "正在查找第"<<mid+1 <<""<<"其值为"<<arr.at(mid)<< endl;
if (arr[mid] == target) {
return mid; // 找到目标值,返回索引
} else if (target < arr[mid]) {
return BinarySearch(arr, target, left, mid - 1); // 在左半部分递归查找
} else {
return BinarySearch(arr, target, mid + 1, right); // 在右半部分递归查找
}
}
template <typename T>
int BinarySearch(const vector<T>& arr, T target) {
return BinarySearch(arr, target, 0, arr.size() - 1);
}
int main() {
vector<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const int index=BinarySearch(l, 9);
cout<<index<<endl;
return 0;
}