8000 Merge pull request #3 from brendanAlbert/master · UN997/python@5d39d7f · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 5d39d7f

Browse files
authored
Merge pull request AllAlgorithms#3 from brendanAlbert/master
Add a binary search algorithm implementation
2 parents 000beb1 + 3051c31 commit 5d39d7f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

sorting/binary_search.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import math
2+
3+
def binary_search(value, list_to_search):
4+
"""
5+
This is a Python implementation of the binary search algorithm.
6+
7+
The binary search algorithm works by looking at the middle element of a list.
8+
The list must be sorted to work correctly.
9+
This implementation uses ascending order.
10+
11+
If the value being searched for is not the middle element, then we check
12+
if the value is smaller or larger than the middle element.
13+
14+
This allows the size of the list being searched to be halved each iteration.
15+
16+
The big O runtime of this algorithm is log(n).
17+
Log(n) is nice because it means that given a huge list, say of 1 million IDs,
18+
it will take no more than 20 iterations to determine if the ID is present.
19+
20+
Arguments: value (that we are searching for), list_to_search (the list)
21+
22+
Return: the value if it is found in the list or -1 if the value is not found.
23+
"""
24+
25+
search_value = -1
26+
max_index = len(list_to_search) - 1
27+
min_index = 0
28+
middle_index = int(math.floor( (max_index + min_index) / 2))
29+
current_element = list_to_search[middle_index]
30+
31+
while max_index >= min_index:
32+
33+
if current_element == value:
34+
return current_element
35+
36+
elif value > current_element:
37+
min_index = middle_index + 1
38+
39+
elif value < current_element:
40+
max_index = middle_index - 1
41+
42+
middle_index = int(math.floor( (min_index + max_index) / 2))
43+
current_element = list_to_search[middle_index]
44 5754 +
45+
return search_value
46+
47+
48+
id_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
49+
short_list = ['allie', 'ben', 'charlie', 'danielle', 'emilio', 'fred', 'gina', 'henry', 'isabella']
50+
print(binary_search('gina', short_list))

0 commit comments

Comments
 (0)
0