Skip to content

Commit 1c61cff

Browse files
committed
Added Binary Search algorithm
1 parent 51053cb commit 1c61cff

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'''
2+
Python 3
3+
4+
Binary search is a really effective search algorithm that requires the searched array to be sorted.
5+
The basic idea is that we all the time split our array in half, and determine which half our wanted item
6+
is located. This way, we continuously cut the area we search in half, and in the end, we will have found our
7+
item.
8+
'''
9+
10+
def binary_search(needle, haystack, low = 0, high = None):
11+
'''
12+
Searches for the needle using the binary search algorithm.
13+
This is a recursive implementation.
14+
:param needle: The item we want to locate
15+
:param haystack: The array in which we want to search for the needle
16+
:param low: The lower limit of where in the haystack we want to search.
17+
:param high: The upper limit of where in the haystack we want to search.
18+
:return: The index of the needle in the haystack, or -1 if it is not present
19+
'''
20+
21+
# If no value for high is specified, we should search until the end of the array
22+
if high == None:
23+
high = len(haystack)
24+
25+
# If the high limit is lower than the low, the haystack does not contain the needle
26+
if high < low:
27+
return -1
28+
29+
# We calculate the mid point of our array (rounding it to closest integer)
30+
mid = int((low + high) / 2)
31+
32+
if haystack[mid] > needle:
33+
# If the middle element is higher than the needle, we need to search the lower half of the haystack
34+
return binary_search(needle, haystack, low, mid - 1)
35+
elif haystack[mid] < needle:
36+
# If the middle element is lower than the needle, we need to search the upper half of the haystack
37+
return binary_search(needle, haystack, mid + 1, high)
38+
else:
39+
# If the middle element is neither lower or higher than the needle, the needle is located in the mid position
40+
return mid
41+
42+
if __name__ == '__main__':
43+
needle = 3
44+
haystack = [0, 1, 2, 3, 4, 5, 6, 7]
45+
index = binary_search(needle, haystack)
46+
print('The result for needle', needle, 'in haystack', haystack, 'is', index)
47+
48+
needle = 0
49+
haystack = [1, 2, 3, 4, 5, 6, 7]
50+
index = binary_search(needle, haystack)
51+
print('The result for needle', needle, 'in haystack', haystack, 'is', index)

0 commit comments

Comments
 (0)