Coding Quiz
This coding quiz is about implementing the binary search algorithm.
Write a program that checks whether a given value exists in a sorted list and returns the index of that value. If the value does not exist, the program should return -1
.
def solution(arr, target):
return # Write your code here
Hint
-
The binary search algorithm only works on a list that is sorted.
-
To find the middle value, you can use
(left index + right index) // 2
. -
Choose the
middle element
of the list, and check if this middle value is the value you're looking for, or if it is smaller or larger. Then, reduce the search range by half and search again. -
You can use loops or recursion.
Based on what you've learned so far, implement the binary search algorithm and check if it passes the test cases.
Click the model answer button at the bottom right to view an example of the function.
Input and Output Examples
Example 1
-
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 7
-
Output: 6
Example 2
-
Input: [1, 3, 5, 7, 9, 11, 13, 15], 4
-
Output: -1
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.