其他分享
首页 > 其他分享> > 二分法查找

二分法查找

作者:互联网

二分法查找

算法说明

int find(int *a, int key, int start, int end) {
    int lowerBound = start;
    int upperBound = end;
    int curIn = 0;

    while (true) {
        curIn = (lowerBound + upperBound) / 2;
        if (a[curIn] == key)
            return curIn;
        else if (lowerBound > upperBound)
            return -1;
        else {
            if (a[curIn] < key)
                lowerBound = curIn + 1;
            else
                upperBound = curIn - 1;
        }
    }
}

测试

#include <iostream> 
using namespace std;

void mySwap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

void selectSort(int *arr, int len) {
    int inner = 0;
    int outer = 0;
    int min = 0;

    // 由于内部是inner = outer+1, 所以外层for循环到len-1即可
    for (outer = 0; outer < len - 1; outer++) {
        min = outer;
        for (inner = outer + 1; inner < len; inner++) {
            if (arr[inner] < arr[min]) {
                min = inner;
            }
        }
        if (min != outer)
            mySwap(arr[outer], arr[min]);
    }  
}

int find(int *a, int key, int start, int end) {
    int lowerBound = start;
    int upperBound = end;
    int curIn = 0;

    while (true) {
        curIn = (lowerBound + upperBound) / 2;
        if (a[curIn] == key)
            return curIn;
        else if (lowerBound > upperBound)
            return -1;
        else {
            if (a[curIn] < key)
                lowerBound = curIn + 1;
            else
                upperBound = curIn - 1;
        }
    }
}

int main() {
    int a[] = { -4, 7, 9, 5, 3, 2, 1, 3};
    int len = (sizeof(a)) / sizeof(a[0]);

    cout << "排序之前: " << endl;
    for (int i = 0; i < len; i++) {
        cout << a[i] << " ";
    }
    cout << endl;

    selectSort(a, len);       

    cout << "排序之后: " << endl;
    for (int i = 0; i < len; i++) {
        cout << a[i] << " ";
    }
    cout << endl;

    int pos = find(a, -4, 0, len - 1);

    cout << "元素位置: " << pos << endl;

    return 0;
}

标签:lowerBound,outer,int,upperBound,二分法,查找,inner,curIn
来源: https://www.cnblogs.com/hesper/p/10666639.html