查找算法的实现 顺序和折半

本文深入探讨了数组查找算法中的顺序查找与折半查找两种方法,详细解释了每种方法的工作原理、实现过程及应用场景。通过实例代码演示,直观展示查找过程,并比较了两种方法的时间复杂度,帮助读者理解不同场景下选择最优查找策略的重要性。

#include<iostream>
#include<stdio.h>


using namespace std;

//对于数组的顺序查找
//int search(int a[],int key,int count ){
// int x = 0;
//
// for (int i = 0; i < count; ++i){
//
// if (a[i] == key)
// {
// ++x;
// cout << "找到了,第" << i << "个位置" << endl;
// }
// }
// cout << "总共出现了" << x << "次" << endl;
//
// return 0;
//}


//对于数组的折半查找


int Half_search(int a[],int key,int count){
int low = 0, high = count;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
cout << "mid" << mid<<endl;
cout << "a[mid]" << a[mid] << endl;
cout << "key" << key << endl;
if (a[mid] == key)
{
cout << "find" << endl;
cout << "a[mid]=" << a[mid] << "," <<"key"<< key << endl;
cout << "第" << mid << "个" << endl;
return mid;
}
else
if (a[mid] < key)
{
low = mid + 1;
}
else
high = mid - 1;
}
cout << "not find" << endl;
return 1;
}


void main(){
int a[10] = {0,2,4,6,8,10,15,17,19,20};
int count = sizeof(a)/sizeof(int);
cout << "count" << count << endl;
int key;


cout << "请输入要查询的关键字:" << endl;


cin >> key;
Half_search(a, key, count);
system("pause");


}

















评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值