-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.py
More file actions
49 lines (41 loc) · 1.01 KB
/
binary_search.py
File metadata and controls
49 lines (41 loc) · 1.01 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
# -*- coding:utf-8 -*-
def binary_search(alist, key):
'''
binary_search by iteration
'''
first = 0
last = len(alist)-1
found = False
index = None
while first <= last and not found:
mid = (last + first) // 2
if alist[mid] == key:
found = True
index = mid
else:
if alist[mid] < key:
first = mid + 1
else:
last = mid - 1
return found, index
def binary_search_recursion(alist, key):
'''
binary_search by recursion
'''
if len(alist) == 0:
return False, None
else:
mid = len(alist) // 2
if alist[mid] == key:
return True, mid
else:
if alist[mid] < key:
return binary_search_recursion(alist[mid+1:], key)
else:
return binary_search_recursion(alist[:mid], key)
a = [1, 3, 5, 7, 9, 11]
b = []
c = [6]
# r, i = binary_search(c, 6)
r, i = binary_search_recursion(b, 6)
print(r, i)