首页 > 代码库 > C++ 二分查找 求最近的值

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>

运行结果: