3376=数据结构实验之查找四:二分查找
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 int queue[100000]; 5 int find(int left,int right,int temp) 6 { 7 if(right<left)return -1; 8 int mid=(left+right)/2; 9 if(temp==queue[mid])return mid; 10 else if(temp<queue[mid]) return find(left,mid-1,temp); 11 else if(temp>queue[mid]) return find(mid+1,right,temp); 12 } 13 int main() 14 { 15 int n,m,i,t; 16 scanf("%d %d",&n,&m); 17 for(i=0;i<n;i++) 18 { 19 scanf("%d",&queue[i]); 20 } 21 /*题目的要求是序号从0开始,因此下标从0开始*/ 22 for(i=1;i<=m;i++) 23 { 24 scanf("%d",&t); 25 printf("%d\n",find(0,n-1,t)); 26 } 27 return 0; 28 }