【演算法學習筆記】-二分尋找演算法

來源:互聯網
上載者:User

標籤:c++   二分尋找   搜尋   

二分搜尋是一種常用的搜尋方法,它要求數組中的元素必須是有序存放的。不失一般性,我們假定數組元素按升序存放。二分搜尋方法首先將關鍵字與位於數組中央的元素進行比較,比較結果有三種情況:
1)如果關鍵字小於中央元素,我們只需要繼續在數組的前半部分進行搜尋。
2)如果關鍵字與中央元素相等,則搜尋結束,找到匹配元素。

3)如果關鍵字大於中央元素,我們只需要繼續在數組的後半部分進行搜尋。

二分搜尋的代碼如下:

#include <iostream>using namespace std;int binarySearch(int a[],int number,int len){int left=0,right=len-1;int middle;while(left<=right){middle=(left+right)/2;if(a[middle]<number){left=middle+1;}else if(a[middle]>number){right=middle-1;}else{return middle;}}return -1;}int _tmain(int argc, _TCHAR* argv[]){int a[]={2,4,7,10,11,45,50,59,60,66,69,70,79};int result=binarySearch(a,45,13);if (result == -1){cout<<"not find this number"<<endl;}else{cout<<"the index of number is "<<result<<endl;}return 0;}
輸出結果為:
the index of number is 5

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【演算法學習筆記】-二分尋找演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.