折半查找

来源:互联网 发布:c语言成员变量 编辑:程序博客网 时间:2024/06/06 10:50

折半查找

#include <bits/stdc++.h>using namespace std;int BinarySerch1 (int * A, const int x, const int n) {    int l = 0;    int r = n - 1;    while (l <= r) {        int m = (l + r) / 2;        if (x < A[m]) r = m - 1;        else if (x > A[m]) l = m + 1;        else return m;//找到x,返回下标m    }    return -1;//没有找到返回-1}//递归版本int BinarySerch2 (int *A, const int x, int l, int r) {    if (l <= r) {        int m = (l + r) / 2;        if (x < A[m]) BinarySerch2 (A, x, l, m - 1);        else if (x > A[m]) BinarySerch2 (A, x, m + 1, r);        else return m;    }    return -1;}int main() {    int A[] = {14, 62, 73, 52, 66, 74, 45, 34, 87, 29};    int len = sizeof (A) / sizeof (A[0]);    sort (A, A + len);//sort函数升序排列    cout << BinarySerch1 (A, 62, len) << endl;    cout << BinarySerch2 (A, 62, 0, len) << endl;}
原创粉丝点击