#include <vector>
#include <iostream>
using namespace std;
int BSearchLowerBound(int array[], int low, int high, int target)
{
if(high < low || target <= array[low]) return -1;
int mid = (low + high + 1) / 2;
while (low < high)
{
if (array[mid] < target)
low = mid;
else
high = mid - 1;
mid = (low + high + 1) / 2;
}
return mid;
}
int BSearchUpperBound(int array[], int low, int high, int target)
{
if(low > high || target >= array[high]) return -1;
int mid = (low + high) / 2;
while (high > low)
{
if (array[mid] > target)
high = mid;
else
low = mid + 1;
mid = (low + high) / 2;
}
return mid;
}
vector<int> SearchRange(int A[], int n, int target)
{
vector<int> r(2, -1);
if (n <= 0) return r;
int lower = BSearchLowerBound(A, 0, n-1, target);
lower = lower + 1;
if(A[lower] == target)
r[0] = lower;
else
return r;
int upper = BSearchUpperBound(A, 0, n-1, target);
upper = upper < 0? (n-1):(upper - 1);
r[1] = upper;
return r;
}
int main(int argc, char** argv)
{
int A[] = {1,2,3,3,3,3,4,5,6,7};
vector<int> v;
int size = sizeof(A)/sizeof(int);
int target = 0;
v = SearchRange(A, size, target);
cout << target << ": " << v[0] << ',' << v[1] << '\n';
target = 1;
v = SearchRange(A, size, target);
cout << target << ": " << v[0] << ',' << v[1] << '\n';
target = 3;
v = SearchRange(A, size, target);
cout << target << ": " << v[0] << ',' << v[1] << '\n';
target = 7;
v = SearchRange(A, size, target);
cout << target << ": " << v[0] << ',' << v[1] << '\n';
target = 8;
v = SearchRange(A, size, target);
cout << target << ": " << v[0] << ',' << v[1] << '\n';
return 0;
}