首页 > 代码库 > 二分查找
二分查找
#include <stdio.h>
int binarySearchRecursion(int arry[],int low,int high,int target);
int binarySearch(int array[],int low,int high,int target);
int main(int argc, const char * argv[]) {
int array[] = {1,3,4,5,6,8,9,11,14,15,18,24,33};
int index = binarySearch(array, 0, 12, 54);
int item = binarySearchRecursion(array, 0, 12, 8);
printf("item = %d\n", item);
if(index == -1) printf("查找的树不存在\n");
else printf("index = %d\n", index);
return 0;
}
int binarySearch(int array[],int low,int high,int target){
if (array == NULL || low >= high) { return -1; }
while(low<=high){
int mid = (low+high)/2;
if(array[mid] > target)
// 一定要记得 -1
high = mid - 1;
else if(array[mid] < target)
low = mid+1;
else // 找到
return mid;
}
// target不存在
return-1;
}
int binarySearchRecursion(int array[],int low,int high, int target){
if (array == NULL || low >= high) {
return -1;
}
int mid = low + (high - low)/2;
if(array[mid] == target)
return mid;
else if(target < array[mid]){
return binarySearchRecursion(array,low,mid-1,target);}
else{
return binarySearchRecursion(array,mid+1, high,target);}
}
int second_find(int array[], int left, int right, int target){
if (array == NULL || (left>right)) {
return -1;
}
int mid = (left+right)/2;
if (array[mid] == target) {
return mid;
}else if(array[mid] >target){
return second_find(array, left, mid-1, target);
}else{
return second_find(array, mid+1, right, target);
}
return 0;
}
二分查找