顺序查找,折半查找
顺序查找,折半查找(注释,标明易错处)
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <iostream>
#define ElemType int
#define MaxSize 10
using namespace std;
//查找:顺序查找,二分查找
void OrderSearch(ElemType A[],int n){//顺序存储的顺序查找
bool flag = false;
int tag;
for(int i=1;;i++){
if(A[i] == n){
flag = true; //find it
tag = i; //the final pos of the target element
break; //got it then no need searching
}
}
if(flag == true){
cout<<"find "<<n<<" at pos "<<tag<<endl;
}
else{
cout<<"not found!"<<endl;
}
}
void BinarySearch(ElemType A[],int n){//顺序存储的二分查找
int mid;
int low,high;
low = 1;
high = 10;
while(low<=high){
mid = (low+high)/2;
if(A[mid] == n) {
cout<<"find "<<n<<" at pos "<<mid<<endl;
return;
}
else if(A[mid] > n) high = mid-1;//target is in the smaller part(front part)
else low = mid+1; //A[mid] < n,target is in the bigger part
}
cout<<"not found!"<<endl;
}
int main(){
clock_t start,end;
//折半查找只适用于有序序列
//顺序、折半查找序列(有序):23 123 159 166 256 299 399 896 989 999,复制此序列输入
int ans = 166;//查找元素为166
ElemType Target[MaxSize];
cout<<"请输入待查找元素序列:"<<endl;
for(int i=1;i<=10;i++) cin>>Target[i];
cout<<"===================================================="<<endl;
cout<<" 顺序查找 "<<endl;
cout<<"===================================================="<<endl;
start = clock();
//for(int k=0;k<10000000;k++){
OrderSearch(Target,ans);//}
end = clock();
cout<<"顺序查找运行时间:"<<double(end-start)/CLOCKS_PER_SEC<<endl;
cout<<"===================================================="<<endl;
cout<<" 折半查找 "<<endl;
cout<<"===================================================="<<endl;
start = clock();
//for(int k=0;k<10000000;k++){
BinarySearch(Target,ans);//}
end = clock();
cout<<"折半查找运行时间:"<<double(end-start)/CLOCKS_PER_SEC<<endl;
return 0;
}
运行调试