Skip to content

Commit f863761

Browse files
committed
PR-2
1 parent 2ec20e6 commit f863761

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Algorithms/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")

Algorithms/LinearSearch.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def linearSearch(arr, x):
2+
pos = -1
3+
for i in range(len(arr)):
4+
if arr[i] == x:
5+
pos = i
6+
print("Found at {}".format(pos))
7+
8+
if pos == -1:
9+
print("Not Found")

0 commit comments

Comments
 (0)