#include <stdio.h> /*
二分查找条件: 1、有序序列 2、数据在数组中
*/ int baseBinarySearch(int a[],int h,int k)
{
int low=;
int high=h;
int mid =;
int NoFound = -;
while (low <= high)
{
mid = low + (high-low) / ;
if ( k < a[mid] )
{
high = mid - ;
}
else if ( k > a[mid] )
{
low = mid + ;
}
else
{
return mid;
}
}
return NoFound;
} //查找第一个相等的元素
int FirstElementBinSearch(int a[],int h,int k)
{
int low=;
int high=h;
int mid =;
int NoFound = -;
while (low <= high)
{
mid = low + (high-low) / ;
if ( k <= a[mid] )
{
high = mid - ;
}
else
{
low = mid + ;
}
}
return low <= h ? low : NoFound;
} //查找最后一个相等的元素low int LastElementBinSearch(int a[],int h,int k)
{
int low=;
int high=h;
int mid =;
int NoFound = -;
while (low <= high)
{
mid = low + (high-low) / ;
if ( k >= a[mid] )
{
low = mid + ;
}
else
{
high = mid - ;
}
}
printf("%d %d %d\n",low,high,a[low-]); if (low - >= && a[low - ] ==k)
{
return low-;
}
return NoFound;
}