假设为升序排列,则二分搜索代码如下:
int i = 0;
int j = n - 1;
while (i < j)
{
if (a[i] == x || a[j] == x)
{
return true;
}
int k = (i + j) / 2;
if (a[k] == x)
{
return true;
}
else if (a[k] < x)
{
j = k;
}
else
{
i = k;
}
}
return false;
void Half_Search(const int *a, int SIZE, int value, int left, int right)
{
if (left > right || value < a[left] || value > a[right] )
{
cout << "No Such Data Found!" << endl << endl ;
return ;
}
int middle = (left + right)/2 ; // middle pointer
if ( value == a[middle] )
{
while (a[--middle] == value) ; // move the pointer to the front position of the leftest certain data