-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
55 lines (52 loc) · 1.27 KB
/
binary_search.cpp
File metadata and controls
55 lines (52 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// =====================================================================================
//
// Filename: binary_search.cpp
//
// Description:
//
// Version: 1.0
// Created: 11/05/2019 01:14:29 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <vector>
class Solution
{
public:
int search(std::vector<int>& nums, int target)
{
int left = 0;
int right = nums.size() - 1;
while (left <= right)
{
int middle = (left + right) / 2;
if (nums[middle] < target)
{
left = middle + 1;
}
else if (nums[middle] > target)
{
right = middle - 1;
}
else
{
// nums[middle] == target
return middle;
}
}
return -1;
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {-1, 0, 3, 5, 9, 12};
int target = 9;
int index = Solution().search(nums, target);
printf("Found %d? %d\n", target, index);
return 0;
}