Skip to content

Commit 3028439

Browse files
committed
Algorithm
1 parent ac06c67 commit 3028439

3 files changed

Lines changed: 38 additions & 96 deletions

File tree

python/Interpolation_Search.py

Lines changed: 0 additions & 96 deletions
This file was deleted.

python/searching/binarysearch.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Returns index of x in arr if present, else -1
2+
# arr is the sorted array that is passed in the function
3+
# x is the element we are searching for,
4+
# l is the leftmost element and r the rightmost.
5+
def binarySearch(arr, l, r, x):
6+
# Check base case
7+
if r >= l:
8+
mid = l + (r - l) // 2
9+
10+
# If element is present at the middle itself
11+
if arr[mid] == x:
12+
return mid
13+
14+
# If element is smaller than mid, then it
15+
# can only be present in left subarray
16+
elif arr[mid] > x:
17+
return binarySearch(arr, l, mid-1, x)
18+
19+
# Else the element can only be present
20+
# in right subarray
21+
else:
22+
return binarySearch(arr, mid + 1, r, x)
23+
24+
else:
25+
# Element is not present in the array
26+
return -1
27+
28+
# Driver Code
29+
arr = [ 2, 3, 4, 10, 40 ]
30+
x = 10
31+
32+
# Function call
33+
result = binarySearch(arr, 0, len(arr)-1, x)
34+
35+
if result != -1:
36+
print ("Element is present at index % d" % result)
37+
else:
38+
print ("Element is not present in array")

0 commit comments

Comments
 (0)