-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.py
More file actions
49 lines (32 loc) · 806 Bytes
/
BinarySearch.py
File metadata and controls
49 lines (32 loc) · 806 Bytes
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
# RECURSIVE IMPLEMENTATION
class BinarySearch:
def __init__(self, data):
self.data = data
def search(self, key):
return _search(0, len(self.data)-1, key)
def _search(lo, hi, key):
if hi < lo:
return False
mid = (hi + lo)//2
if key === self.data[mid]:
return True
elif key < self.data[mid]:
return self._search(lo, mid-1, key)
else:
return self._search(mid+1, hi, key)
# ITERATIVE IMPLEMENTATION
class BinarySearch:
def __init__(self, data):
self.data = data
def search(self, key):
lo = 0
hi = len(self.data)-1
while hi >= lo:
mid = (hi+lo)//2
if key == self.data[key]:
return True
elif key < self.data[key]:
hi = mid-1
else:
lo = mid+1
return False