/* * BinarySearch.c * * Created on: 2014年6月25日 * Author: wenbo */ #include <stdio.h> int binarySearch(int arr[],int num,int length){ int l = 0,u = length-1; int curr = 0; while(l<=u){ curr = (u+l)/2; if(arr[curr]==num){ printf("index of the num is:%d\n",curr); return curr; } if(arr[curr]<num){ l = curr+1; } if(arr[curr]>num){ u = curr-1; } } printf("can't find the number.\n"); return -1; } int main(){ int a[10] = {1,2,3,4,5,65,77,88,99,1001}; binarySearch(a,1,10); binarySearch(a,65,10); binarySearch(a,1001,10); binarySearch(a,100,10); return 0; }
【C/C++】BinarySearch
时间: 2024-10-12 03:26:26