forked from Adityaranjanpatra/Btecky2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSomnath1
66 lines (48 loc) · 1.29 KB
/
Somnath1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import turtle
def binary_search(array, target):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
def draw_binary_search(array, target):
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.write("Binary Search")
turtle.forward(100)
for i in range(len(array)):
turtle.penup()
turtle.goto(i * 10, array[i] * 10)
turtle.pendown()
turtle.write(f"{array[i]}")
turtle.penup()
turtle.goto(0, array[target] * 10)
turtle.pendown()
turtle.write(f"Target: {target}")
# Perform binary search
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
turtle.penup()
turtle.goto(mid * 10, array[mid] * 10)
turtle.pendown()
turtle.write(f"Mid: {array[mid]}")
if array[mid] == target:
turtle.write(f"Found! at index {mid}")
break
elif array[mid] < target:
low = mid + 1
else:
high = mid - 1
turtle.hideturtle()
array = [1, 3, 5, 7, 9]
target = 7
draw_binary_search(array, target)