-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
46 lines (37 loc) · 1.07 KB
/
binary_search.cpp
File metadata and controls
46 lines (37 loc) · 1.07 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
#include <iostream>
using namespace std;
int binary_search(int input[], int length, int number){ //length -> input's size
int start = 0;
int end = length - 1;
while(end >= start){
int middle = (start + end) / 2;
if(input[middle] == number){
return 1;
}
if(input[middle] < number){
start = middle + 1;
}
if(input[middle] > number){
end = middle - 1;
}
}
return 0;
}
int binary_search_recursive(int input[], int length, int start, int end, int number){ //length -> input's size
int middle = (start + end) / 2;
if(start > end){
return 0;
} else {
if(input[middle] == number){
return 1;
} else {
if(input[middle] > number){
end = middle - 1;
binary_search_recursive(input, length, start, end, number);
} else {
start = middle + 1;
binary_search_recursive(input, length, start, end, number);
}
}
}
}