-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.cpp
39 lines (38 loc) · 1014 Bytes
/
binary_search.cpp
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
#include<iostream>
using namespace std;
int BS_recursive(int [],int,int ,int);
int BS_iterative(int [],int,int, int);
int main(){
int x[]={1,2,3,4,5,6,7,8,9,10};
int r=BS_recursive(x,0,9,9);
int s=BS_iterative(x,0,9,9);
cout<<r<<s;
return 0;
}
int BS_recursive(int sorted_list[], int low, int high, int element)
{
if (high < low)
return -1;
middle = low + (high - low)/2;
if (element < sorted_list[middle])
return BS_recursive(sorted_list, low, middle-1, element);
else if (element > sorted_list[middle])
return BS_recursive(sorted_list, middle+1, high, element);
else
return middle;
}
int BS_iterative(int sorted_list[], int low, int high, int element)
{
int middle;
while (low <= high)
{
middle = low + (high - low)/2;
if (element > sorted_list[middle])
low = middle + 1;
else if (element < sorted_list[middle])
high = middle - 1;
else
return middle;
}
return -1;
}