递归二分法
// 递归算法
int recrbinary(int * a,int key ,int low, int high)
{
int mid;
if (low > high) {
return - 1;
}
mid = (low + high) / 2;
if (a[mid] == key) {
return mid;
}else if (a[mid] > key)
{
return recrbinary(a, key, low, mid - 1);
}else
{
return recrbinary(a, key, mid + 1, high);
}
}
###非递归算法
int binary(int * a, int key, int n)
{
int left = 0, right = n - 1, mid = 0;
mid = (left + right) / 2;
while (left < right && a[mid] != key) {
if (a[mid] < key)
{
if (a[mid] < key) {
left = mid + 1;
}else if (a[mid] > key){
right = mid - 1;
}
mid = (left + right) / 2;
}
}
if (a[mid] == key) {
return mid;
}
return -1;
}
网友评论