码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 二分查找 求最近的值

时间:2014-07-29 22:00:42      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:c++   二分查找   

上代码:

<span style="font-size:18px;"> #include <iostream>
 #include <math.h>

using namespace std;

int BinarySearch(float *array, int aSize, float key)
{
if ( array == NULL || aSize == 0 )
      return -1;

int low = 0;
int high = aSize - 1;
int mid = 0;

int minIndex=0;
int gap=abs(array[mid]-key);

   while ( low <= high )
   {
        mid = (low + high )/2;
        if(gap>abs(array[mid]-key))
		{
			gap=abs(array[mid]-key);
			minIndex=mid;
		}
        if ( array[mid] < key)
		{   
               low = mid + 1;
		}
        else if ( array[mid] > key )   
            { 
				high = mid - 1;
		    }
        else
		{ 
            return (minIndex-1);
		}
    }
    
}

int main()
{
	float array[6]={1.02,2.03,3.06,8.49,12.63,88.47};

	for(int i=0;i<sizeof(array)/sizeof(float);i++)
		cout<<array[i]<<" ";
	cout<<endl;

    cout<<"No recursive:"<<endl;
    cout<<"position:"<<BinarySearch(array, 4, 12.90)<<endl;

	system("pause");
    return 0;
}
</span>

运行结果:
bubuko.com,布布扣





C++ 二分查找 求最近的值,布布扣,bubuko.com

C++ 二分查找 求最近的值

标签:c++   二分查找   

原文地址:http://blog.csdn.net/u013476464/article/details/38276861

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!