顺序查找,折半查找

顺序查找,折半查找

顺序查找,折半查找(注释,标明易错处)

#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;
} 

运行调试
运行调试

2019.02.28 数据结构学习 ZaneLing

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值