Created
May 19, 2016 09:20
-
-
Save thien/67fd1012b8ecc11a3848362da585b0eb to your computer and use it in GitHub Desktop.
An iterative and recursive approach to BinarySearch in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def binarySearch(A, i): | |
L = 0 | |
R = len(A)-1 | |
found = -1 | |
while L <= R and found == -1: | |
M = (L + R)//2 | |
if A[M] == i: | |
found = M | |
else: | |
if i < A[M]: | |
R = M-1 | |
else: | |
L = M+1 | |
return found | |
def binarySearch2(A, i): | |
return binarySearchR(A, 0, len(A)-1, i) | |
def binarySearchR(a, start, end, target): | |
middle = (start + end) // 2 | |
if end < start: | |
return -1 | |
if target == a[middle]: | |
return middle | |
elif target < a[middle]: | |
return binarySearchR(a, start, middle - 1, target) | |
else: | |
return binarySearchR(a, middle + 1, end, target) | |
a = [1,1,1,1,1,1,1,2,3,3,3,3,7] | |
print(binarySearch(a,2)) | |
print(binarySearch2(a,2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment