二分查找法

2017-08-09  本文已影响0人  写自己的代码

二分查找法

int binarySearch(int a[],int n,int key) {
    int low = 0,mid,high = n - 1;
    while(low <= high) {
        mid = (low + high)/2;
        printf("mid=%d\n",mid);
        if (key < a[mid]) {
            high = mid - 1;
        } else if (key > a[mid]) {
            low = mid +1;
        } else {
            return mid;
        }
    }
    
    return -1;
}

二分查找法(递归)

int binarySearch(int a[],int n,int low,int high,int key) {
    int low = 0,mid,high = n - 1;
    if(low <= high) {
        mid = (low + high)/2;
        printf("mid=%d\n",mid);
        if (key < a[mid]) {
            return binarySearch(a,n,low,mid-1,key);
        } else if (key > a[mid]) {
            return binarySearch(a,n,mid+1,high,key);
        } else {
            return mid;
        }
    }
    
    return -1;
}
上一篇下一篇

猜你喜欢

热点阅读