#include <iostream>

//  Bsearch - 二分法查找 - 开始
template<typename Data>
int Bsearch(Data *a, Data v, int s, int e, int (*compare)(Data, Data)) {
    while(s <= e) {
        int m = (s+e)/2;
        int c = compare(a[m], v);
        if(!c) return m;
        if(c<0) s = m+1;
        else    e = m-1;
    }
    return -1;
}
//  Bsearch - 二分法查找 - 结束

int main() {
    const char *s[] = {
        "abort",
        "broad",
        "count",
        "discount",
        "enough",
        "fire",
        "good",
        "hire",
        "inspect",
        "jump",
        "kick",
        "help"
    };
    printf("%s at %d\n", s[5], Bsearch(s, s[5], 0, 11, strcmp));
    printf("%s at %d\n", s[9], Bsearch(s, s[9], 0, 11, strcmp));
    printf("%s at %d\n", s[6], Bsearch(s, s[6], 0, 11, strcmp));
}

一͛世͛珍͛藏͛
86 声望6 粉丝

« 上一篇
二叉树
下一篇 »
gdb (lldb)