-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
79 lines (53 loc) · 1.33 KB
/
binarysearch.cpp
File metadata and controls
79 lines (53 loc) · 1.33 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
using namespace std;
int list[] = {10,20,30,40,50,60,70,80,90,100 };
int recur_binary(int start , int end , int number){
int mid = (start + end) / 2;
if( start > end)
return -1;
if( list[mid] == number)
return mid;
else if( list[mid] > number )
return recur_binary(start , mid-1,number);
else if( list[mid] < number )
return recur_binary(mid+1 , end,number);
}
int iter_binary(int start , int end , int number){
while( start <= end )
{
int mid = (start + end) / 2;
if(list[mid] == number)
return mid;
else if( list[mid] > number )
end = mid-1;
else if( list[mid] < number )
start = mid+1;
}
return -1;
}
int main(){
int input;
int n;
while(1){
cout << " Enter an integer to search : " ;
cin >> n;
cout << "Enter method of search: (1. Binary Search 2. Recursive binary search) : ";
cin >> input;
if ( input == 1){
int result = iter_binary(0 , 9 , n);
if( result == -1 )
cout << n << " is NOT FOUND" << endl;
else{
cout << n << " is at position " << result << endl;
}
}
else if( input == 2){
int result = recur_binary(0 , 9 , n);
if( result == -1 )
cout << n << " is NOT FOUND" << endl;
else{
cout << n << " is at position " << result << endl;
}
}
}
}