Skip to content

Commit ac33a2c

Browse files
Added Binary Search
1 parent f499bde commit ac33a2c

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

binarysearch.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import math
2+
3+
4+
def bs_itr(A, n, key):
5+
low = 0
6+
high = n - 1
7+
8+
while low <= high:
9+
mid = math.floor((low + high)/2)
10+
11+
if key == A[mid]:
12+
return mid
13+
elif key < A[mid]:
14+
high = mid - 1
15+
elif key > A[mid]:
16+
low = mid + 1
17+
18+
return "Not Found"
19+
20+
21+
A = [1, 2, 3, 4, 5, 6, 7]
22+
23+
print(A)
24+
print("Iterative Binary Search output:", bs_itr(A, len(A), 10))
25+
print("Iterative Binary Search output:", bs_itr(A, len(A), 5))
26+
print("Iterative Binary Search output:", bs_itr(A, len(A), 2))
27+
28+
29+
def bs_recur(A, key, low = 0, high = len(A) - 1):
30+
if low > high:
31+
return "Not Found"
32+
else:
33+
mid = math.floor((low + high)/2)
34+
35+
if key == A[mid]:
36+
return mid
37+
elif key < A[mid]:
38+
return bs_recur(A, key, low, mid - 1)
39+
elif key > A[mid]:
40+
return bs_recur(A, key, mid + 1, high)
41+
42+
43+
print("Recursive Binary Search output:", bs_recur(A, 10))
44+
print("Recursive Binary Search output:", bs_recur(A, 5))
45+
print("Recursive Binary Search output:", bs_recur(A, 2))

fact.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def factorialofN(n):
2+
if n == 0:
3+
return 1
4+
else:
5+
return factorialofN(n-1) * n
6+
7+
print(factorialofN(7))

0 commit comments

Comments
 (0)