Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions binary_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Binary Search in python


def binarySearch(array, x, low, high):

if high >= low:

mid = low + (high - low)//2

# If found at mid, then return it
if array[mid] == x:
return mid

# Search the left half
elif array[mid] > x:
return binarySearch(array, x, low, mid-1)

# Search the right half
else:
return binarySearch(array, x, mid + 1, high)

else:
return -1


array = [3, 4, 5, 6, 7, 8, 9]
x = 4

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")