from: http://blog.csdn.net/yake25/article/details/7346249
#include <iostream>
#include <vector>
#include <fstream>
#include <ctime>
using namespace std;
int low(vector<int> &ivec, int left, int right, int x)
{
while(left < right)
{
int mid = (left + right) / 2;
if(ivec[mid] < x)
left = mid + 1;
else
right = mid;
}
return left;
}
int upper(vector<int> &ivec, int left, int right, int x)
{
while(left < right)
{
int mid = (left + right) / 2;
if(ivec[mid] > x)
right = mid;
else
left = mid + 1;
}
return right;
}
int main()
{
clock_t begin = clock();
int n, x, left, right, first = 0, last = 0;
vector<int> ivec;
ifstream infile("input2.txt");
while(infile >> n)
ivec.push_back(n);
cout << "Input x: " << endl;
cin >> x;
left = 0;
right = ivec.size();
while(left < right)
{
int mid = (left + right) / 2;
if(ivec[mid] < x)
left = mid + 1;
else if(ivec[mid] > x)
right = mid + 1;
else
{
first = low(ivec, left, right, x);
cout << first << endl;
last = upper(ivec, left, right, x);
break;
}
}
cout << "Numbers: " << last - first << endl;
clock_t endtime = clock();
cout << "Time: " << (double)(endtime - begin) << endl;
}