# EP2 Binary Search

• 查元素的位置
• 元素不存在的时候，在哪个位置插入
• 元素多个存在的时候，查元素存在的上下限
``````
#include <iostream>
#include <vector>

using namespace std;

/*

*/

int lower1(const vector<int>& v, int target) {
int l = 0, r = v.size() - 1;
while (l <= r) {
int m = (r - l) / 2 + l;
if (v[m] >= target) {
r = m - 1;
} else {
l = m + 1;
}
}

return l;
}

int upper1(const vector<int>& v, int target) {
int l = 0, r = v.size() - 1;
while (l <= r) {
int m = (r - l) / 2 + l;

if (v[m] > target) {
r = m - 1;
} else {
l = m + 1;
}
}

return l - 1;
}

/*

*/
int lower(const vector<int>& v, int target) {
int l = 0, r = v.size();
while (l < r) {
int m = (r - l) / 2 + l;

if (v[m] >= target) {
r = m;
} else {
l = m + 1;
}
}

return l;
}

int upper(const vector<int>& v, int target) {
int l = 0, r = v.size();
while (l < r) {
int m = (r - l) / 2 + l;

if (v[m] > target) {
r = m;
} else {
l = m + 1;
}
}

return l - 1;
}

int main()
{
cout<<"Hello World";

vector<int> v{0, 1, 2, 3, 4, 5, 6};
int low = lower(v, 4);
int up = upper(v, 4);

cout << "low: " << low << ", up: " << up << endl;

int low1 = lower1(v, 4);
int up1 = upper1(v, 4);

cout << "low1: " << low1 << ", up1: " << up1 << endl;

return 0;
}

``````

``````int findMinInSortedAndRotatedArray(vector<int> nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] > nums[r]) l = mid + 1;
else r = mid;
}
return l;
}

``````