设a[0:n-1]是已排好序的数组,请改写二分搜索算法,使得当x不在数组中时,返回小于x的最大元素位置i和大于x的最小元素位置j。当搜索元素在数组中时,i和j相同,均为x在数组中的位置。
// Ctest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int search(int a[], int length, int x)
{
int i = 0, j = 0;
int detection = -1;//标志位
int top = length - 1;//数组的有边界
int middle = 0;//中间值的下标
int low = 0;//数组的左边界
while (low <= top)
{
middle = (low + top) / 2;
if (a[middle] == x)
detection = middle;
if (a[middle] < x)
low = middle + 1;
else
top = middle - 1;
}
if (detection == -1)
{
i = top;
j = low;
}
else
{
i = detection;
j = i;
}
cout << "i的值为:" << i << endl;
cout << "j的值为:" << j << endl;
return 0;
}
int main()
{
int arr[] = { 1,2,4,5,78,90 };
int length = sizeof(arr) / sizeof(int);
search(arr, length,3 );
system("pause");
return 0;
}