修饰一下

This commit is contained in:
2024-12-22 01:27:31 +08:00
parent 04e9780b47
commit f746c7cf86
+9 -9
View File
@@ -5,33 +5,33 @@
using namespace std;
template <typename T>
int BinarySearch(const vector<T>& arr, T target, int left, int right) {
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 <<""<<"其值为"<<arr.at(mid)<< endl;
cout << "正在查找第"<<mid+1 <<""<<"其值为"<<l.at(mid)<< endl;
if (arr[mid] == target) {
if (l[mid] == value) {
return mid; // 找到目标值,返回索引
} else if (target < arr[mid]) {
return BinarySearch(arr, target, left, mid - 1); // 在左半部分递归查找
} else if (value < l.at(mid)) {
return BinarySearch(l, value, left, mid - 1); // 在左半部分递归查找
} else {
return BinarySearch(arr, target, mid + 1, right); // 在右半部分递归查找
return BinarySearch(l, value, mid + 1, right); // 在右半部分递归查找
}
}
template <typename T>
int BinarySearch(const vector<T>& arr, T target) {
return BinarySearch(arr, target, 0, arr.size() - 1);
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};
const int index=BinarySearch(l, 9);
int index=BinarySearch(l, 9);
cout<<index<<endl;
return 0;
}