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 elementof 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
Lessons in this chapter ยท Object-Oriented Programming, Data Structures, and Basic Algorithms
- 1. What is Object-Oriented Programming?
- 2. Defining the Beginning, End, and Behavior of Objects
- 3. Extending Class Functionality Through Inheritance
- 4. Encapsulation and Polymorphism, Core Concepts of Object-Oriented Programming
- 5. Fill-in-the-blank quiz
- 6. Data Structures for Systematic Data Management
- 7. Piling Up Like Plates(Stack)
- 8. Standing in Line, Queue
- 9. Dynamically Connecting Data with Linked Lists
- 10. Managing Data with Keys and Values using a Hash Table
- 11. What is a Tree?
- 12. Multiple-choice quiz
- 13. What is an Algorithm?
- 14. Fast and Efficient Search Method, Binary Search
- 15. Coding Quiz - Implementing Binary Search Algorithm
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help