CodeTestValidate

No installations needed! Write Python directly in your browser and get instant feedback with our smart validation system.

Challenge # 3

Binary Search

Objective

Implement the binary search algorithm to efficiently locate a target value in a sorted list.

Instructions

  • You are given a sorted list of integers called nums and a target integer target.

  • Implement a function binary_search(nums, target) that returns the index of target if it is present in the list.

  • If the target is not found, return -1.

  • Use the binary search algorithm, not linear search.

  • Assume the input list nums is already sorted in ascending order.

Constraints:
Do not use input(). • `nums` will be a list of integers sorted in ascending order. • `target` will be an integer.
Exemple IO

Input: nums = [1, 3, 5, 7, 9, 11] target = 5

Output: 2

Input: nums = [1, 3, 5, 7, 9, 11] target = 6

Output: -1

Input: nums = [] target = 4

Output: -1

Input: nums = [2, 4, 6, 8, 10] target = 2

Output: 0

Try It Online!

Output:

Validate Your Results

Get your code reviewed and validated to understand what you did right and where you can improve.

Previous challengeBubble Sort and Insertion SortNext challengeFind the Second-Largest Number
Loading...