问题:设a[0:n-1]是已排好序的数组,请改写二分搜索算法,使得当x不在数组中时,返回小于x的最大元素位置i和大于x的最小元素位置j。当搜索元素在数组中时,i和j相同,均为x在数组中的位置。
思路:二分搜索算法是将n个元素分成大致相同的两半然后将x与中间位置比较,如果相等则停止搜索,如果小于中间值则在左半部再次搜索,如果大于中间值则在右半部搜索,止到找到或者满足循环停止的条件为止。 代码如下: C++
#include<iostream>
using namespace std;
int binarySearch(int a[], int x, int left, int right, int &i, int &j){
int mid;
while(left <= right){
mid = (left+right)/2;
if(x == a[mid]){
i = j = mid;
return 1;
}
if(x > a[mid])
left = mid +1;
else
right = mid - 1;
}
i = right;
j = left;
return 0;
}
int main(){
int n,a[1000],x,i,j;
cout<<"输入元素个数:";
cin>>n;
cout<<"请输入"<<n<<"个元素";
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<"输入需要查找的数:";
cin>>x;
if(binarySearch(a,x,0,n,i,j))
cout<<x<<"在数组的位置:"<<i<<endl;
else
cout<<x<<"不在数组内,小于和大于的最大元素位置分别为"<<i<<" "<<j<<endl;
}
C
#include<stdio.h>
int binarySearch(int a[],int x,int left,int right,int *small,int *big){
int middle;
while(left<=right){
middle = (left+right)/2;
if(x == a[middle]){
*small = left;
return 1;
}
if(x > a[middle]) left = middle+1;
else right = middle-1;
}
*small=right;
*big=left;
return 0;
}
int main(){
int a[]={2,4,6,8,10,12};
int small,big;
int temp = binarySearch(a,8,0,5,&small,&big);
if(temp == 1){
printf("有值,位置(下标):%d\n",small);
}
else{
printf("无此值,小:%d;大:%d\n",small,big);
}
return 0;
}
|