二分查詢演算法

Diy_os發表於2015-12-08
關於二分法查詢,也經常稱折半查詢,思想就是“分而治之”,網上有很多資料,給出維基百科上的連結(),本文不作贅述。下面給出二分查詢的非遞迴和遞迴的演算法。

點選(此處)摺疊或開啟

  1. #include<iostream>
  2. using namespace std;
  3. int search(int *, int, int);
  4. int searchfdg(int *, int, int, int);
  5. int search(int *arra, int key, int high) {
  6.     int low = 0;
  7.     while (low <= high)
  8.     {
  9.         int mid = (low + high) / 2;
  10.           if (arra[mid] == key) {
  11.             return mid;
  12.          }else if (arra[mid] > key) {
  13.             high = mid - 1;
  14.          }else
  15.             low = mid + 1;
  16.     }
  17.     cout << "元素不存在!";
  18.         return -1;
  19. }
  20.   
  21. int searchfdg(int *arra, int key,int low,int high) {
  22.       
  23.         if (low <= high)
  24.         {
  25.             int mid = (low + high) / 2;
  26.             if (key == arra[mid]){
  27.                 return mid;
  28.             }
  29.             else if (key < arra[mid]) {
  30.                 return searchfdg(arra, key, low, mid - 1);
  31.             }else if (key > arra[mid])
  32.                 low = mid + 1;
  33.                 return searchfdg(arra, key, mid+1,high);
  34.         }
  35.         else
  36.             cout << "元素不存在!";
  37.             return -1;
  38.     }
  39. int main() {
  40.     int arra[] = {3,5,9,14,17,23,29,33,37 };
  41.     int size = sizeof(arra) / sizeof(int);
  42.     cout << "非遞迴查詢的元素在陣列中的位置是:" << endl;
  43.     cout << search(arra, 33, size-1) << endl;
  44.     cout << "遞迴查詢的元素在陣列中的位置是:" << endl;
  45.     cout << searchfdg(arra, 33, 0,size-1) << endl; //注意此時的low和high的值
  46.   
  47. }
執行結果:

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29876893/viewspace-1868404/,如需轉載,請註明出處,否則將追究法律責任。

相關文章