靜態表尋找練習

來源:互聯網
上載者:User

實現代碼:

#include <iostream>#include <vector>using namespace std;template<class T>/************************************************************************//* 無序靜態表順序尋找                                           *//************************************************************************/int seqSearch(vector<T> &data, const T &x){//哨兵data[0]=x;int i=0;for (i=data.size()-1;data[i]!=x;i--);return i;}/************************************************************************//* 有序靜態表二分尋找                                           *//************************************************************************/template<class T>int binarySearch(vector<T> &data, const T &x){int low=0;int high=data.size()-1;int mid=(low+high)/2;//如果需要某一個變數來動態只是一個資料,但是在迴圈中不能很好處理且//只差一次,這個時候可以把這個變數在迴圈外處理一次,或者加個前端節點//來解決(二叉樹和鏈表中)!!!while (low<=high){if(data[mid]==x)return mid;if(x<data[mid])high=mid-1;elselow=mid+1;mid=(high+low)/2;}return 0;}

測試代碼:

int main(){vector<int> seq;seq.push_back(0);seq.push_back(1);seq.push_back(2);seq.push_back(3);seq.push_back(4);seq.push_back(5);seq.push_back(6);seq.push_back(7);cout << seqSearch(seq,3) << endl;cout << seqSearch(seq,10)<< endl;cout << binarySearch(seq,5) << endl;cout << binarySearch(seq,20)<< endl;return 0;}

 

聯繫我們

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