折半查找的实现

来源:互联网 发布:郑大新校区淘宝地址 编辑:程序博客网 时间:2024/05/17 08:29

折半查找法的两种实现

折半查找法:

在有序表中,把待查找数据值与查找范围的中间元素值进行比较,会有三种情况出现:

1)     待查找数据值与中间元素值正好相等,则放回中间元素值的索引。

2)     待查找数据值比中间元素值小,则以整个查找范围的前半部分作为新的查找范围,执行1),直到找到相等的值。

3)     待查找数据值比中间元素值大,则以整个查找范围的后半部分作为新的查找范围,执行1),直到找到相等的值

4)     如果最后找不到相等的值,则返回错误提示信息。

 

按照二叉树来理解:中间值为二叉树的根,前半部分为左子树,后半部分为右子树。折半查找法的查找次数正好为该值所在的层数。等概率情况下,约为

log2(n+1)-1

 

[cpp] view plaincopy
  1. //Data为要查找的数组,x为待查找数据值,beg为查找范围起始,last为查找范围终止  
  2.   
  3. //非递归法  
  4. int BiSearch(int data[], const int x, int beg, int last)  
  5. {  
  6.     int mid;//中间位置  
  7.     if (beg > last)  
  8.     {  
  9.         return -1;  
  10.     }  
  11.       
  12.   
  13.     while(beg <= last)  
  14.     {  
  15.         mid = (beg + last) / 2;  
  16.         if (x == data[mid] )  
  17.         {  
  18.             return mid;  
  19.         }  
  20.         else if (data[mid] < x)  
  21.         {  
  22.             beg = mid + 1;  
  23.         }  
  24.         else if (data[mid] > x)  
  25.         {  
  26.             last = mid - 1;  
  27.         }  
  28.     }  
  29.     return -1;  
  30. }  
  31.   
  32.   
  33.   
  34. //递归法  
  35. int IterBiSearch(int data[], const int x, int beg, int last)  
  36. {  
  37.     int mid = -1;  
  38.     mid = (beg + last) / 2;  
  39.     if (x == data[mid])  
  40.     {  
  41.         return mid;  
  42.     }  
  43.     else if (x < data[mid])  
  44.     {  
  45.         return IterBiSearch(data, x, beg, mid - 1);  
  46.     }  
  47.     else if (x > data[mid])  
  48.     {  
  49.         return IterBiSearch(data, x, mid + 1, last);  
  50.     }  
  51.     return -1;  
  52. }  
  53.   
  54. //主函数  
  55. int _tmain(int argc, _TCHAR* argv[])  
  56. {  
  57.     int data1[60] = {0};  
  58.     int no2search = 45;  
  59.   
  60.     cout << "The array is : " << endl;  
  61.     int siz = sizeof(data1)/sizeof(int);  
  62.     for (int i = 0; i < siz; i++)  
  63.     {  
  64.         data1[i] = i;  
  65.         cout << data1[i] << " ";  
  66.     }  
  67.     cout << endl;  
  68.       
  69.     int index = -1;  
  70.     //index = BiSearch(data1, no2search, 0, siz);  
  71.     index = IterBiSearch(data1, no2search, 0, siz);  
  72.     cout << "Index of " << no2search << " is " << index << endl;  
  73.   
  74.     getchar();  
  75.     return 0;  
  76. }  
0 0
原创粉丝点击