打卡4

问题描述:N个有序整数数列已放在一维数组中,利用二分查找法查找整数m在数组中的位置。若找到,则输出其下标值;反之,则输出“Not be found!”。

流程图:

 

伪代码:

N<-10

a[N]<-{10个有序整数}

k<-1

input m

whlie low<=high

mid=(low+high)/2

if m<a[mid]

high<-mid-1

else if m>a[mid]

low<-mid+1

else

k=mid

break

if k<0

output “Not be found!”

else

output k,m

代码:

#include <iostream>

#define N 10

using namespace std;

int main()

{

int a[N]={3,14,33,52,64,77,98,111,231,314};

int low=0;

int k=-1;

int high=N-1;

int m,mid,i;

cin>>m;

for(i=0;i<N;i++)

{

cout<<a[i]<<"  ";

}

cout<<endl;

while(low<=high)

{

mid=(low+high)/2;

if(m<a[mid])

{

high=mid-1;

}

else if(m>a[mid])

{

low=mid+1;

}

else

{

k=mid;

break;

}

}

if(k<0)

cout<<"Not be found!"<<endl;

else

cout<<""<<k+1<<",下标值="<<m;

return 0;

}

 

posted @ 2023-04-27 20:57  umiQa  阅读(11)  评论(0编辑  收藏  举报