//折半查找算法
#include <iostream>
using namespace std;
int search(int a[],int n,int x); //函數聲明
int main()
{
int i,x,z;
int a[10];
cout<<"Please enter 10 numbers:"<<endl;
for(i=0;i<10;i++) //輸入10個整數
cin>>a[i];
cout<<"Please enter your search number:"<<endl;
cin>>x; //輸入要查找的數字
z=search(a,10,x);
if(!z) //equal if(z==0)
cout<<"The number you search is not in a[i]!"<<endl;
else
cout<<x<<" is "<<z<<"th number in a[i]."<<endl;
return 0;
}
int search(int a[],int n,int x) //折半查找函數
{
int low,mid,high;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==x)
return mid+1; //返回找到的數字在數組中的位置
else if(a[mid]>x)
high=mid-1;
else
low=mid+1;
}
return 0; //如果沒找到就返回0
}
C++版基本算法2--折半查找
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
從DT到Random Forest、GBDT
lightty
2020-07-04 15:28:07
C++版基本算法3--分塊查找
smartdust
2020-06-27 16:11:50
C++版排序算法1--選擇排序
smartdust
2020-02-24 04:52:15
C++版基本算法1--順序查找
smartdust
2020-02-24 04:52:15
從DT到Random Forest、GBDT
lightty
2020-07-04 15:28:07
C++版基本算法3--分塊查找
smartdust
2020-06-27 16:11:50
C++版排序算法1--選擇排序
smartdust
2020-02-24 04:52:15
C++版基本算法4-哈希查找
smartdust
2020-02-24 04:52:15
C++版基本算法1--順序查找
smartdust
2020-02-24 04:52:15
Device Tree
mobz
2020-02-23 12:55:37
23.從物理執行的角度透視 spark job
yangshihao321
2018-08-30 16:14:38
RDDTransformation Ops
yangshihao321
2018-08-30 16:14:38
RDD創建徹底解密
yangshihao321
2018-08-30 16:14:37
TopNGroup
yangshihao321
2018-08-30 16:14:22
ETL講解(很詳細!!!)
rzsgsj
2018-08-29 23:38:22