设:a[0:n-1]是一个已排好序的数组。请改写二分搜索算法,使得当搜索元素x不在数组中时,返回小于x的最大元素的位置I和大于x的最小元素位置J。当搜索元素在数组中时,I和J相同,均为x在数组中的位置。
二分搜索算法如下:
给定已按升序排好序的n个元素a[0:n-1],现要在这n个元素中找出一特定元素x。
template<class Type>
int BinarySearch(Type a[], const Type& x, int l, int r)
{
while(r>=l)
{
int m=(l+r)/2;
if(x==a[m]) return m;
if(x<a[m]) r=m-1; else=m+1;
}
return -1;
}
改写如下:
#include<iostream>
using namespace std;
int BinarySearch(int a[], int n, int x, int& i, int& j)
//a[]为数组,n为元素个数,x为查找的数字,i、j为位置
{
int middle;
int right=n-1;
int left=0;
while(left<=right)
{
middle=(left+right)/2;
if(x==a[middle])
{
i=j=middle;
return 0;
}
if(x>a[middle])
left=middle+1;
else
right=middle-1;
}
i=right;
j=left;
return -1;
}
int main()
{
int i, j, x, k;
int a[]={2,4,6,8,10};
cout<<"原始数据为"<<endl;
for(k=0; k<sizeof(a)/sizeof(int); k++)
cout<<""<<a[k];
cout <<endl;
cout<<"请输入待查找数据"<<endl;
cin>>x;
BinarySearch(a, 5, x, i ,j);
if(BinarySearch(a, 5, x, i, j)==-1)
{
cout<<"not find"<<endl;
cout<<"最大元素位置"<<i<<endl;
cout<<"最小元素位置"<<j<<endl;
}
else
cout<<"find the value"<<i<<endl;
return 0;
}