1. 程式人生 > >binary_search,lower_bound, upper_bound的實現和c++調庫

binary_search,lower_bound, upper_bound的實現和c++調庫

自己實現


#include <bits/stdc++.h>
using namespace std;
// 在數組裡面查詢值為val的索引,如果有多個值為val,隨即返回一個索引;如果沒有返回-1.
int binary_search(int *a, int n, int val)
{
    int left = 0, right = n, mid;
    while(left < right)
    {
        mid = (left+right)/2;   // 更嚴謹的寫法是 mid=(right-left)/2+left;
        if(a[mid] == val) return mid;
        if(a[mid] < val) left=mid+1;
        if(a[mid] > val) right=mid;
    }
    return -1;
}

// 在數組裡面查詢值為val的索引,如果有多個值為val,隨即最小的索引;如果沒有返回-1.
int lower_bound(int *a, int n, int val)
{
    int left = 0, right = n, mid;
    while(left < right)
    {
        mid = (left+right)/2;
        if(a[mid]>=val) right=mid;
        else left=mid+1;
    }
    if(a[left]!=val) return -1;
    return left;
}

// 在數組裡面查詢值為val的索引,如果有多個值為val,隨即最大的索引;如果沒有返回-1.
int upper_bound(int *a, int n, int val)
{
    int left = 0, right = n, mid;
    while(left < right)
    {
        mid = (left+right)/2;
        if(a[mid]<=val) left=mid+1;
        else right=mid;
    }
    if(a[left]!=val) return -1;
    return left;
}

int main()
{
    int a[] = {1, 2, 2, 3, 3, 3, 4, 4, 7, 7};
    int index1 = binary_search(a, 10, 3); // 4
    int index2 = lower_bound(a, 10, 0);   // 3
    int index3 = upper_bound(a, 10, 0);   // 5
    cout << index1 << endl << index2 << endl << index3 << endl;
    return 0;
}

c++調庫

/*
lower_bound(起始地址,結束地址,要查詢的數值) 返回的是數值 第一個 出現的位置。

upper_bound(起始地址,結束地址,要查詢的數值) 返回的是數值 大於最後一個 出現的位置。

binary_search(起始地址,結束地址,要查詢的數值)  返回的是是否存在這麼一個數,是一個bool值。
 */
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int a[] = {1, 2, 2, 4, 5, 5, 5, 9};
    int index1 = lower_bound(a, a+8, 5)-a; // 4
    int index2 = upper_bound(a, a+8, 5)-a; // 7 注意!!!回的是數值 大於最後一個 出現的位置。
    bool index3 = binary_search(a, a+8, 5); // 1
    cout << index1 << endl;
    cout << index2 << endl;
    cout << index3 << endl;
    return 0;
}