二分查找法

实现思路:

1、从数组的中间开始寻找,如果中间的数据小于要寻找的目标则从中间往右边寻找,继续是从右边的中间开始。

2、从数组的中间开始寻找,如果中间的数据大于要寻找的目标则从中间往左边寻找,继续是从左边的中间开始。

前提:在使用二分查找的时候数组是用先排序好的,递增和递减都可以。

 

具体代码如下:

#include <iostream>

using namespace std;


/***********************************************************
 * 非递归实现二分查找
 * @参数
 * @source:要查找的目标数组
 * @low:数组的最小的下标
 * @high:数组的最大的下标
 * @target:要查找的目标
 * *********************************************************/
 int bisect_serach(int *source,int low,int high,int target)
 {
    int mid = 0;
    while(low <= high)
    {
        mid = (low+high)/2;
        if(source[mid]>target)
        {
            high = mid-1;
        }
        else if(source[mid]<target)
        {
            low = mid+1;
        }
        else if(source[mid]==target)
            return mid;
    }
   return -1; //没有找到
 }



 /***********************************************************
  * 递归实现二分查找
  * @参数
  * @source:要查找的目标数组
  * @low:数组的最小的下标
  * @high:数组的最大的下标
  * @target:要查找的目标
  * *********************************************************/
  int bisect_serach_rec(int *source,int low,int high,int target)
  {
     int mid = 0;
     mid = (low+high)/2;
     if (low > high)
         return -1; //没有找到

     else if(source[mid]>target)
     {
       bisect_serach_rec(source,low,mid-1,target);
     }
     else if(source[mid]<target)
     {
         bisect_serach_rec(source,mid+1,high,target);
     }

     else if(source[mid]==target)
         return mid;

  }


int main()
{
   int i = 0;
   int position;
   int *source = new int[10];
   for(i=0;i<10;i++)
       source[i] = i;

    position = bisect_serach(source,0,9,22);
    if(position == -1)
    {
      cout<<"not found the data"<<endl;
    }
    cout<<position<<endl;
    delete []source;
    return 0;
}

 

posted @ 2018-03-26 15:07  沙漠里的孤鲸  阅读(141)  评论(0编辑  收藏  举报