Binary Search 2/2
It is time to test your first Binary search algorithm!
Use hints if needed! Scroll down to see the full code! Be careful with the tabulation!
Task
Swipe to start coding
- Test the function with the
x
variable. - Print the result for the 1st test.
- Test the function with the
x_2
variable. - Print the result for the 2nd test.
Solution
99
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
def binarySearch(array, left, right, x):
if right >= left:
middle = left + (right - left) // 2
if array[middle] == x:
return middle
elif array[middle] > x:
return binarySearch(array, left, middle - 1, x)
else:
return binarySearch(array, middle + 1, right, x)
else:
return 'The element was not found'
# Test array
arr = [5, 7, 10, 12, 6]
# Test the function with the 'x' variable
x = 12
test = binarySearch(arr, 0, len(arr) - 1, x)
print(test)
# Test the function with the 'x_2' variable
x_2 = 20
test_2 = binarySearch(arr, 0, len(arr) - 1, x_2)
print(test_2)
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 2
99
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
def binarySearch(array, left, right, x):
if right >= left:
middle = left + (right - left) // 2
if array[middle] == x:
return middle
elif array[middle] > x:
return binarySearch(array, left, middle - 1, x)
else:
return binarySearch(array, middle + 1, right, x)
else:
return 'The element was not found'
# Test array
arr = [5, 7, 10, 12, 6]
# Test the function with the 'x' variable
x = 12
test = _ _ _(_ _ _, 0, len(arr)-1, _ _ _)
# Print the result for the 1st test
print(_ _ _)
# Test the function with the 'x_2' variable
x_2 = 20
test_2 = _ _ _(arr, _ _ _, _ _ _, _ _ _)
# Print the result for the 2nd test
_ _ _
Ask AI
Ask anything or try one of the suggested questions to begin our chat