实验六完成
This commit is contained in:
+1
-1
@@ -13,7 +13,7 @@ int seqSearch(vector<T> l,T value) {
|
|||||||
bool found = false;
|
bool found = false;
|
||||||
int index = 0;
|
int index = 0;
|
||||||
for (int i=0; i<l.size(); i++) {
|
for (int i=0; i<l.size(); i++) {
|
||||||
cout<<"正在顺序查找第"<<i<<"位元素"<<"其值为"<<l.at(i)<<endl;
|
cout<<"正在顺序查找第"<<i+1<<"位元素"<<"其值为"<<l.at(i)<<endl;
|
||||||
|
|
||||||
if (l.at(i) == value) {
|
if (l.at(i) == value) {
|
||||||
found = true;
|
found = true;
|
||||||
|
|||||||
+18
-18
@@ -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) {
|
||||||
void ListBinaryCopy(vector<T> p,vector<T> sl,vector<T> sr) {
|
if (left > right) {
|
||||||
int low=0;
|
return -1; // 未找到目标值
|
||||||
int high=p.size()-1;
|
|
||||||
int mid=(low+high)/2;
|
|
||||||
|
|
||||||
for (int i=low;i<=mid;i++) {
|
|
||||||
sl[i]=p[i];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i=mid+1;i<=high;i++) {
|
int mid = left + (right - left) / 2; // 计算中间位置
|
||||||
sr[i]=p[i];
|
|
||||||
|
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>
|
template <typename T>
|
||||||
int BinarySearch(vector<T> l, T value) {
|
int BinarySearch(const vector<T>& arr, T target) {
|
||||||
if (l.empty()) return -1;
|
return BinarySearch(arr, target, 0, arr.size() - 1);
|
||||||
|
|
||||||
vector<T> sub_list_left, sub_list_right;
|
|
||||||
ListBinaryCopy(l, sub_list_left);
|
|
||||||
|
|
||||||
BinarySearch(sub_list_left, value);
|
|
||||||
BinarySearch(sub_list_right, value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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);
|
||||||
|
cout<<index<<endl;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user