二分法查找

来源:互联网 发布:迷雾影评知乎 编辑:程序博客网 时间:2024/05/13 14:13
  1. /********************************************************************
  2. created:    2009/01/01
  3. created:    1:1:2009   17:28
  4. author:     ZhangLiang
  5. purpose:    二分法
  6. *********************************************************************/
  7. #include "stdafx.h"
  8. //////////////////////////////////////////////////////////////////////////
  9. //overload operator
  10. list<int>::iterator operator +(list<int>::iterator it,int n)
  11. {
  12.     for (int i = 0;i<n;i++)
  13.     {
  14.         it++;
  15.     }
  16.     return it;
  17. }
  18. //////////////////////////////////////////////////////////////////////////
  19. //get the mid value of one value 
  20. inline int AverageValue(int count)
  21. {
  22.     if ( 1==count%2)
  23.     {
  24.         return (count+1)/2;
  25.     }
  26.     else
  27.     {
  28.         return count/2;
  29.     }
  30. }
  31. //////////////////////////////////////////////////////////////////////////
  32. //二分法
  33. //valuelist: the value collection
  34. // count: value count
  35. //findvalue: the value be finded
  36. //the iterator finded
  37. int Dichotomy(list<int>& valuelist,int count,int findvalue,list<int>::iterator* pit)
  38. {
  39.     int nCount = AverageValue(count);
  40.     if (1== count)
  41.     {
  42.         if ( findvalue == *(*pit))
  43.         {
  44.             *pit = *pit +1;
  45.         }
  46.         else
  47.         {
  48.             return 0;
  49.         }
  50.     }
  51.     if (findvalue == *(*pit+(nCount-1)))
  52.     {
  53.         *pit = *pit+(nCount-1);
  54.         return 1;
  55.     }
  56.     else if (findvalue < *(*pit+(nCount-1)))
  57.     {
  58.         return Dichotomy(valuelist,nCount,findvalue,pit);
  59.     }
  60.     else if (findvalue>*(*pit+(nCount-1)))
  61.     {
  62.         *pit = *pit+nCount;
  63.         return Dichotomy(valuelist,nCount,findvalue,pit);
  64.     }
  65. }
  66. //////////////////////////////////////////////////////////////////////////
  67. //main function
  68. int _tmain(int argc, _TCHAR* argv[])
  69. {
  70.     list<int> lstValues;
  71.     int nCount = 20;
  72.     for (int i =0;i<nCount;i++)
  73.     {
  74.         lstValues.push_back(i);
  75.     }
  76.     int nValue =7;
  77.     list<int>::iterator it = lstValues.begin();
  78.     int ret = Dichotomy(lstValues,nCount,nValue,&it);
  79.     if (ret == 1)
  80.     {
  81.         cout<<*it<<'/n';
  82.     }
  83.     else
  84.     {
  85.         cout<<"No Value/n";
  86.     }
  87.     system("pause");
  88.     return 0;
  89. }

 

原创粉丝点击