1152: 二分搜索 非递归与递归

来源:互联网 发布:怎么开淘宝福利群 编辑:程序博客网 时间:2024/06/18 09:32

1152: 二分搜索

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 1736  Solved: 634

SubmitStatusWeb Board

Description

在有序序列中查找某一元素x。

Input

首先输入一个正整数n(n<=100000),表示该序列有n个整数,然后按从小到大的顺序输入n个整数;

接着是一个正整数m,表示有m次查找;

最后是m个整数,表示m个要查找的整数x。

Output

对于每一次查找,有一行输出。若序列中存在要查找的元素x,则输出元素x在序列中的序号(序号从0开始);若序列中不存在要查找的元素x,则输出"Not found!"。

Sample Input

51 3 5 7 9 11-112345678910

Sample Output

Not found!0Not found!1Not found!2Not found!3Not found!4Not found!

HINT

//非递归

#include<iostream>using namespace std;int  a[100000]={0};int  Bsearch(int a[],int x,int n);int  main (){            int  n,m,i,x,k=0;cin>>n;for ( i=0;i<n;i++){cin>>a[i];}        cin>>m;    for (i=0;i<m;i++){   cin>>x;   k=Bsearch(a,x,n);   if (k)   cout<<k-1<<endl;   else   cout<<"Not found!"<<endl;}return 0;}int  Bsearch(int a[],int x,int n){       int  low,high,mid;       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;}


//递归调用

#include<iostream>int a[100000]={0};using namespace std;int  Bsearch(int a[],int x,int low,int high);int  main (){            int  n,m,i,x;cin>>n;for ( i=0;i<n;i++){cin>>a[i];}        cin>>m;    while (m--){   cin>>x;   int k=Bsearch(a,x,0,n-1);   if (k==-1)   {   cout<<"Not found!"<<endl;       continue;   }   else   {   cout<<k<<endl;       continue;   }}return 0;}int  Bsearch(int a[],int x,int low,int high){          if (low>high)  return -1;  else  {  int mid=( low + high )/2;               if ( x==a[mid] )   return mid;   else if( x < a[mid])   return Bsearch(a,x,low,mid-1);   else   return Bsearch(a,x,mid+1,high);  } }



原创粉丝点击