8000 Merge pull request #4 from RanadeepPolavarapu/master · UN997/python@1db8c55 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1db8c55

Browse files
authored
Merge pull request AllAlgorithms#4 from RanadeepPolavarapu/master
feat(searches): add linear and binary search
2 parents 5d39d7f + 9e44c11 commit 1db8c55

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

searches/binary_search.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def binarySearch(arr, l, r, x): # l is left, r is right, x is search item
2+
if r >= l:
3+
4+
mid = l + (r - l)/2
5+
6+
# If element is present at the middle itself
7+
if arr[mid] == x:
8+
return mid
9+
10+
# If element is smaller than mid, then it
11+
# can only be present in left subarray
12+
elif arr[mid] > x:
13+
return binarySearch(arr, l, mid-1, x)
14+
15+
# Else the element can only be present
16+
# in right subarray
17+
else:
18+
return binarySearch(arr, mid+1, r, x)
19+
20+
else:
21+
# Element is not present in the array
22+
return -1
23+
24+
# Tests
25+
result = binarySearch([ 2, 3, 4, 10, 40 ], 0, len(arr)-1, 10)
26+
print(result)

searches/linear_search.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def linear_search(arr, item):
2+
for i in range(len(arr)):
3+
if arr[i] == item:
4+
return i
5+
return -1
6+
7+
# Tests
8+
9+
print(search([1,2,3,4,5], 3))

0 commit comments

Comments
 (0)
0