数据结构与算法(C++)之折半查找迭代算法

折半查找迭代算法:

#include <iostream>
//迭代的方法:
using namespace std;
//*a传递数组,x为传递的要查找的数,n为数据的个数
int erfen(int *a,const int x,const int n);
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10};
int o;
int num=9;
o=erfen(a,num,10);
if(o<0)
{
cout<<"对不起没有找到!"<<endl;
}
else {
cout<<"在a["<<o<<"]中找到"<<num<<endl;
}
return 0;
}
int erfen(int *a,const int x,const int n)
{
int left=0,right=n-1;

while(left<=right){
int mid=(left+right)/2;
if(x<a[mid]) right=mid-1;
else if(x>a[mid]) left=mid+1;
else return mid;

}
return -1;
}

原文链接: https://www.cnblogs.com/wslQAQ/p/12330049.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    数据结构与算法(C++)之折半查找迭代算法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/330444

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午5:35
下一篇 2023年3月1日 下午5:35

相关推荐