Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Binary Search 2/2 | Binary Search
Binary Search in Python

book
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

  1. Test the function with the x variable.
  2. Print the result for the 1st test.
  3. Test the function with the x_2 variable.
  4. Print the result for the 2nd test.

Solution

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?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 2
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

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt