查找之折半查找
折半查找的前提是有序的,与中间值进行比较,如果有序的则返回;否则,改变始末位置,再进行查找
实现方法:1 循环实现 2 递归实现
1 循环实现
#include<stdio.h> int binary_search(int *array,int n,int data); int main() { int array[10]={ 1,2,3,4,5,6,7,8,9,10 }; printf("please input the number that you want search\n"); int num; scanf("%d",&num); int result=binary_search(array,10,num); if(result==-1) { printf("not found %d\n",num); } else printf("the index is %d\n",result); } int binary_search(int *array,int n,int data) { int start,end,mid; start=0; end=n-1; while(start<=end) { mid=(start+end)/2; if(array[mid]==data) { return mid; } else if(array[mid]>data) { end=mid-1; } else { start=mid+1; } } return -1; } 2 递归实现 int binary_search2(int *array,int start,int end ,int value) { if(start>end) return -1; int mid=(start+end)/2; if(array[mid]==value) { return mid; } else if(array[mid]>value) { binary_search2(array,start,mid-1,value); } else binary_search2(array,mid+1,end,value); }