修饰一下
This commit is contained in:
+9
-9
@@ -5,33 +5,33 @@
|
|||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
template <typename T>
|
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) {
|
if (left > right) {
|
||||||
return -1; // 未找到目标值
|
return -1; // 未找到目标值
|
||||||
}
|
}
|
||||||
|
|
||||||
int mid = left + (right - left) / 2; // 计算中间位置
|
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; // 找到目标值,返回索引
|
return mid; // 找到目标值,返回索引
|
||||||
} else if (target < arr[mid]) {
|
} else if (value < l.at(mid)) {
|
||||||
return BinarySearch(arr, target, left, mid - 1); // 在左半部分递归查找
|
return BinarySearch(l, value, left, mid - 1); // 在左半部分递归查找
|
||||||
} else {
|
} else {
|
||||||
return BinarySearch(arr, target, mid + 1, right); // 在右半部分递归查找
|
return BinarySearch(l, value, mid + 1, right); // 在右半部分递归查找
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
int BinarySearch(const vector<T>& arr, T target) {
|
int BinarySearch(vector<T> l, T value) {
|
||||||
return BinarySearch(arr, target, 0, arr.size() - 1);
|
return BinarySearch(l,value, 0, l.size() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
vector<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
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;
|
cout<<index<<endl;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user