二分查找(分治)
对N个整数进行查找,获取给出的数在该组数据中的位置
#include<stdio.h> int binary_search(int Array[],int N,int num); int main() { int Array[1000]={0}; int N,k,index; int i; scanf("%d",&N); for(i=0;i<N;i++) scanf("%d",&Array[i]); /////排序(从小到大) //selection_sort(Array,N); scanf("%d",&k);//升序数组Array[]中二分搜索 index=binary_search(Array,N,k); printf("这是第%d个数\n",index+1); return 0; } int binary_search(int Array[],int N,int num)//二分查找 { int low,high,mid; low=0; high=N-1; while(low<=high) { mid=(low+high)/2; if(Array[mid]==num) return mid; else if(Array[mid]>num) high=mid-1; else low=mid+1; } return -2;//没在该组数据中会输出-1 }