Created
June 17, 2020 16:12
-
-
Save umangshrestha/2fc1e3dd9ea275afd7867d0890af1147 to your computer and use it in GitHub Desktop.
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
from time import time | |
def calculate_time(f): | |
def wrapper(*args, **kwargs): | |
initial_time = time() | |
output = f(*args, **kwargs) | |
time_taken = time() - initial_time | |
print("the time taken by {function} is {time} and output is {output}".format(function=f.__name__, time=time_taken, output=output)) | |
return output | |
return wrapper | |
@calculate_time | |
def binarySearch(array, element): | |
low = 0 | |
high = len(array) - 1 | |
while low <= high: | |
mid = low + (high - low) //2 | |
if array[mid] == element: | |
return mid | |
elif array[mid] < element: | |
low = mid +1 | |
else: | |
high = mid - 1 | |
return -1 | |
@calculate_time | |
def binarySearchRecursion(array, element): | |
return binarySearchRecurr(array, element) | |
def binarySearchRecurr(array, element): | |
print(array) | |
low = 0 | |
high = len(array) - 1 | |
if low >high: | |
return -1 | |
mid = low + (high - low)//2 | |
if array[mid] == element: | |
return mid | |
elif array[mid] > element: | |
return binarySearchRecurr(array[:mid], element) | |
else: | |
return binarySearchRecurr(array[mid+1:], element) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment