C语言二分查找(折半查找)代码

时间:2014-12-08 15:33    点击:

    #include <stdio.h>
    binarySearch(int a[], int n, int key){
    int low = 0;
    int high = n - 1;
    while(low<= high){
    int mid = (low + high)/2;
    int midVal = a[mid];
    if(midVal<key)
    low = mid + 1;
    else if(midVal>key)
    high = mid - 1;
    else
    return mid;
    }
    return -1;
    }
    int main(){
    int i, val, ret;
    int a[8]={-32, 12, 16, 24, 36, 45, 59, 98};
    for(i=0; i<8; i++)
    printf("%d\t", a[i]);
    printf("\n请输人所要查找的元素:");
    scanf("%d",&val);
    ret = binarySearch(a,8,val);
    if(-1 == ret)
    printf("查找失败 \n");
    else
    printf ("查找成功 \n");
    return 0;
    }

来源:未知//所属分类:C语言/更新时间:2014-12-08 15:33
顶一下
(8)
100%
踩一下
(0)
0%
上一篇:C语言顺序查找算法代码
下一篇:没有了
相关内容