首页 > 代码库 > C语言-二分法入门

C语言-二分法入门

输入十个数,求中间的….

#include<cstdio>int binary_search(int arr[],int SizeOfArray,int key);int binary_search(int arr[],int SizeOfArray,int key){    int left=0,mid;    int right=SizeOfArray-1;    while(left<=right){        mid=(left+right)/2;        if(key==arr[mid])           printf("%d",mid);           break;        if(key<arr[mid])            right=mid-1;        if(key>arr[mid])            left=mid+1;    }    return -1;}int main(){    int key;    scanf("%d",&key);    int a[10]={1,2,3,4,5,6,7,8,9,10};    binary_search(a,9,key);    return 0;}

测试

/* 1 2 3 4 5 6 7 8 9 */

C语言-二分法入门