思路非常easy,代码凝视已标注
#include <stdio.h>
//递归二分查找
int binarySearch(int*start,int *end,intfindData){
if (start > end) { // 递归边界条件
return -1;
}
int *mid = start + (end - start)/2; //依据中间值不断二分缩小待查元素所在范围
if (findData == *mid) {
return *mid;
}else if(findData > *mid){
return binarySearch(mid+ 1, end, findData);
}else{
return binarySearch(start,mid - 1, findData);
}
}
//非递归二分查找
int binarySearchRec(int*start,int *end,intfindData){
if (start == NULL){
return -1;
}
while (start <= end) { //递归使用边界条件终止递归,非递归使用循环条件来终止
int *mid = start + (end - start)/2; // 求中间指针
if (findData == *mid) {
return *mid;
}else if(findData > *mid){
start = mid + 1;
}else{
end = mid - 1;
}
}
return -1;
}
int main(intargc, const char* argv[])
{
int array[] = {2,4,6,8,10,14,15,19}; // num =8,二分查找的前提条件是元素有序的
int len = sizeof(array)/sizeof(int);
printf("递归二分查找binarySearch:%d\n",binarySearch(array,array+ len - 1,100));
printf("非递归二分查找binarySearchRec:%d\n",binarySearch(array,array + len - 1,19));
return 0;
}