标签:style blog http color io 使用 ar 文件 2014
二分查找的迭代和递归实现:
#include <stdio.h>
#include <stdlib.h>
int find1(int *a, int low , int high , int key)//迭代二分查找
{
int mid = 0;
while (low <= high)
{
mid = (low+high)/2;
if (a[mid] == key)
return mid;
else if (a[mid] < key)
low = mid + 1;
else
high = mid -1;
}
return -1;
}
int find2(int *a, int low , int high , int key) //递归二分查找
{
if (low > high)
return -1;
int mid = (low+high)/2;
if (a[mid] == key)
return mid;
else if (a[mid] < key)
find1(a,mid+1,high,key);
else
find1(a,low,mid-1,key);
}
int main()
{
int array[13] = {2,6,8,12,32,64,67,78,98,104,120,134,140};
int key = find2(array,0,12,140);
printf("%d\n",array[key]);
return 0;
}
标签:style blog http color io 使用 ar 文件 2014
原文地址:http://www.cnblogs.com/l6241425/p/3972027.html