程序包括查找第一个和最后一个出现的数字位置。
#include <iostream>
#include <vector>
using namespace std;
int BinarySearch(vector<int> &num,int left,int right,int key){
if(left > right)
return -1;
int mid = (left+right)/2;
if(num[mid] == key)
return mid; //如果要找第一个或者最后一个出现的key,在这个if里再细分
else if(num[mid] < key)
return BinarySearch(num,mid+1,right,key);
else
return BinarySearch(num,left,mid-1,key);
return -1;
}
//查找第一个出现的key
int BinarySearchFirst(vector<int> &num,int left,int right,int key){
if(left > right)
return -1;
int mid = (left+right)/2;
if(num[mid] == key){
if(mid==left || num[mid-1]!=key)
return mid;
else
return BinarySearch(num,left,mid-1,key);
}
else if(num[mid] < key)
return BinarySearch(num,mid+1,right,key);
else
return BinarySearch(num,left,mid-1,key);
return -1;
}
//查找最后一个出现的key
int BinarySearchLast(vector<int> &num,int left,int right,int key){
if(left > right)
return -1;
int mid = (left+right)/2;
if(num[mid] == key){
if(mid==right || num[mid+1]!=key)
return mid;
else
return BinarySearch(num,mid+1,right,key);
}
else if(num[mid] < key)
return BinarySearch(num,mid+1,right,key);
else
return BinarySearch(num,left,mid-1,key);
return -1;
}
int main(){
int a[] = {1,1,2,3,4,5,5,5,7,8,12,15,16,23};
vector<int> input(begin(a),end(a));
int left = 0;
int right = input.size()-1;
int find = BinarySearch(input,left,right,5);
int find1 = BinarySearchFirst(input,left,right,5);
int find2 = BinarySearchLast(input,left,right,5);
cout<<find<<endl;
cout<<find1<<endl;
cout<<find2<<endl;
system("pause");
return 0;
}