(经典) K&R的名著<<C程序设计语言>>二分查找

#include<stdio.h>

//查找成功则返回所在下标否则返回-1
int binsearch(int A[], int n,int a)
{
   int low, high, mid;
   low = 0;
   high = n -1;
   while ( low <= high) {    /// 这里必须是 <=
        mid = (low+high) / 2;
        if (A[mid] == a)
           return mid;
        else if(A[mid]<a)
           low = mid +1;
        else
           high=mid-1;
    }
   return -1;
}


int main()
{   int a[]={1,2,44,44,99};
    printf("%d",binsearch(a,5,44));
}
//二分查找,递归算法
#include <iostream>
#include<stdio.h>

using namespace std;

int binSearch(int a[],int low,int high,int b)
{
    int mid = (high-low)/2;
    if(a[mid] == b) return mid;

    if(a[mid] > b)  binSearch(a,low,mid-1,b);

    if(a[mid] < b)  binSearch(a,mid+1,high,b);
}


int main()
{   int a[] = {2,6,8,88888,88888888}; int yy;
    yy = binSearch(a,0,4,8);
    printf("%d",yy);
    return 0;
}

 

posted on 2017-06-25 15:27  多情剑客无情剑;  阅读(250)  评论(1编辑  收藏  举报

导航