#include <iostream>
using namespace std;
int find1(int *a, int start, int end, int b)
{//给定一个有序序列a,求任意一个i使得a[i]等于b,不存在返回-1.
int mid;
while(start<=end){
mid = start + (end-start)/2;
if(a[mid]<b){
start = mid+1;
}else if(a[mid] > b){
end = mid-1;
}else{
return mid;
}
}
return -1;
}
int find2(int *a, int start, int end, int b)
{// 给定一个有序序列a,求任意最小的i使得a[i]等于b,不存在返回-1.
int mid ;
while((start+1) < end){
mid = start+(end-start)/2;
if(a[mid] >= b)
end = mid;
else
start = mid;
}
if(a[end] == b) return end;
else if(a[start]==b) return start;
else return -1;
}
int find3(int *a, int start, int end, int b)
{// 给定一个有序序列a,求任意最大的i使得a[i]等于b,不存在返回-1.
int mid ;
while((start+1) < end){
mid = start+(end-start)/2;
if(a[mid] > b)
end = mid;
else
start = mid;
}
if(a[end] == b) return end;
else if(a[start]==b) return start;
else return -1;
}
int find4(int *a, int start, int end, int b)
{// 给定一个有序序列a,求任意最大的i使得a[i]小于b,不存在返回-1.
int mid ;
while((start+1) < end){
mid = start+(end-start)/2;
if(a[mid] < b)
start = mid;
else
end = mid;
}
if(a[start]<b && a[end]>=b) return start;
else if(a[end]<b) return end;
else return -1;
}
int find5(int*a, int start, int end, int b)
{//给定一个有序数组a,求最小的i使得a[i]大于b,不存在则返回-1.
int mid;
while((start+1) < end){
mid = start + (end-start)/2;
if(a[mid] > b) end = mid;
else start = mid;
}
if(a[start] > b) return start;
else if(a[start]<=b && a[end]>b) return end;
else return -1;
}
int main()
{
int a1[]={1,2,3,4,4,5};
int a2[]={1,2,2,2,2,3};
int a3[]={1,2,3,4,5,6};
int b = 4;
cout<<find5(a2,0,5,10)<<endl;
cout<<find5(a3,0,5,4)<<endl;
return 0;
}
编程之美,3.11程序改错, 二分扩展
最新推荐文章于 2019-04-14 21:00:38 发布