binary_search lower_bound upper_bound

來源:互聯網
上載者:User

今天看《code complete》的時候突然想起了二分尋找
很久沒用過binary_search這個東西了
又想起最早編程的時候分不清 lower_bound 和 upper_bound 的區別 (不過個人覺得名字起的不好也是一個原因 lower upper這種單詞很容易混淆的)

binary_search:判斷是否存在某個對象
lower_bound: 返回>=對象的第一個位置,lower_bound(2)=3, lower_bound(3)=3
目標對象存在即為目標對象的位置,不存在則為後一個位置.
upper_bound: 返回>對象的第一個位置, upper_bound(2)=3,upper_bound(3)=4
無論是否存在都為後一個位置.

STL裡的用法就不多說了
自己寫了一個最簡單的實現

測了一下 個人覺得沒有問題

int binary_search( int *r, int size, int k )
{
    int low=0, high=size-1, mid;
    while( low <= high )
    {
        mid = (low + high)/2;
        if( r[mid] == k )
            return mid;
        else if( r[mid] < k )
            low = mid + 1;
        else
            high = mid -1;
    }
    return -1;
}

int lower_bound( int *r, int size, int k )
{
    int low=0, high=size-1, mid;
    while( low < high )
    {
        mid = (low + high) / 2;
        if( k > r[mid] )
            low = mid + 1;
        else
            high = mid;
    }
   
    return low;
}

int upper_bound( int *r, int size, int k )
{
    int low=0, high=size-1, mid;
    while( low < high )
    {
        mid = (low + high) / 2;
        if( k < r[mid] )
            high = mid;
           
        else
            low = mid + 1;
           
    }
   
    return low;
}

恩 繼續學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.