改成vector了
This commit is contained in:
+7
-7
@@ -1,25 +1,25 @@
|
|||||||
// 编写一个程序,输出在顺序表(3,6,2,10,l,8,5,7,4,9) 中采用顺序查找方法查找关键字5的过程。
|
// 编写一个程序,输出在顺序表(3,6,2,10,l,8,5,7,4,9) 中采用顺序查找方法查找关键字5的过程。
|
||||||
#include <list>
|
#include <vector>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
int seqSearch(list<T> l,T value) {
|
int seqSearch(vector<T> l,T value) {
|
||||||
if (l.empty()) {
|
if (l.empty()) {
|
||||||
cout << "空表" << endl;
|
cout << "空表" << endl;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
bool found = false;
|
bool found = false;
|
||||||
int index = 0;
|
int index = 0;
|
||||||
for (typename list<T>::iterator it = l.begin(); it != l.end(); ++it) {
|
for (int i=0; i<l.size(); i++) {
|
||||||
cout<<"正在顺序查找第"<<index<<"位元素"<<"其值为"<<*it<<endl;
|
cout<<"正在顺序查找第"<<i<<"位元素"<<"其值为"<<l.at(i)<<endl;
|
||||||
|
|
||||||
if (*it == value) {
|
if (l.at(i) == value) {
|
||||||
found = true;
|
found = true;
|
||||||
|
index = i;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
index++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!found) {
|
if (!found) {
|
||||||
@@ -32,7 +32,7 @@ int seqSearch(list<T> l,T value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
list<int> l={3,6,2,10,'l',8,5,7,4,9};
|
vector<int> l={3,6,2,10,'l',8,5,7,4,9};
|
||||||
int index=seqSearch(l,5);
|
int index=seqSearch(l,5);
|
||||||
cout<<index<<endl;
|
cout<<index<<endl;
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
+30
-2
@@ -1,9 +1,37 @@
|
|||||||
// 编写一个程序,输出在顺序表(1,2, 3, 4, 5, 6, 7, 8, 9, 10)中采用折半查找方法查找关键字9的过程。
|
// 编写一个程序,输出在顺序表(1,2, 3, 4, 5, 6, 7, 8, 9, 10)中采用折半查找方法查找关键字9的过程。
|
||||||
#include<iostream>
|
#include<iostream>
|
||||||
#include<list>
|
#include<vector>
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
|
||||||
|
void ListBinaryCopy(vector<T> p,vector<T> sl,vector<T> sr) {
|
||||||
|
int low=0;
|
||||||
|
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++) {
|
||||||
|
sr[i]=p[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
int BinarySearch(vector<T> l, T value) {
|
||||||
|
if (l.empty()) return -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};
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user