有序数组的二分法查找:
1.递归 二分法查找;
2,非递归 二分法查找;
以下代码 在vs2010 测试通过:
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
//非递归法 二分法查找
int unrecursive_binary_search(int *arr,int arrLength,int value){
int low,high,mid;
low = 0;
high = arrLength-1;
mid = (low+high)/2;
while(low <= high){
if(arr[mid] > value){
high = mid-1;
mid = (low+high)/2;
}else if(arr[mid] < value){
low = mid+1;
mid = (low+high)/2;
}else{
return mid;
}
}
if(low > high){
return -1;
}
}
//递归法 二分查找
int recursive_binary_search(int *arr,int low,int high,int value){
int mid;
mid = (low+high)/2;
if(low <= high){
if(arr[mid] > value){
recursive_binary_search(arr,low,mid-1,value);
}else if(arr[mid] < value){
recursive_binary_search(arr,mid+1,high,value);
}else{
return mid;
}
}else{
return -1;
}
}
int _tmain(int argc, _TCHAR* argv[]){
int arr[] = {0,1,16,24,35,47,59,62,73,88,99};
int result1,result2 ;
int length;
length = sizeof(arr)/sizeof(int);
//二分法 的递归查找
result1 = recursive_binary_search(arr,0,length-1,62);
if(result1 != -1){
printf("递归法 查找成功!\n");
}else{
printf("该值不存在!\n");
}
//二分法的非递归查找
result2 = unrecursive_binary_search(arr,length,62);
if(result2 != -1){
printf("非递归法 查找成功!\n");
}else{
printf("该值不存在!\n");
}
system("pause");
return 0;
}