Tutorialspoint
Problem
Solution
Submissions

Binary Search Algorithm

Certification: Advanced Level Accuracy: 100% Submissions: 3 Points: 15

Write a Python function that implements the binary search algorithm to find a target element in a sorted list. The function should return the index of the target if found, or -1 if the target is not in the list. Implement both iterative and recursive versions of the algorithm.

Example 1
  • Input: sorted_list = [1, 3, 5, 7, 9, 11, 13, 15], target = 7
  • Output: 3
  • Explanation:
    • Step 1: Take the input list and target.
    • Step 2: Perform binary search.
    • Step 3: Return the index of the target if found, else -1.
Example 2
  • Input: sorted_list = [2, 4, 6, 8, 10, 12], target = 5
  • Output: -1
  • Explanation:
    • Step 1: Take the input list and target.
    • Step 2: Perform binary search.
    • Step 3: Return the index of the target if found, else -1.
Constraints
  • The input list is sorted in ascending order.
  • The list can contain only integers.
  • 0 ≤ list length ≤ 10^6
  • Time Complexity: O(log n), where n is the length of the list.
  • Space Complexity: O(1) for iterative version, O(log n) for recursive version (due to call stack).
Functions / MethodsRecursionGoogleTutorialspoint
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Binary search involves repeatedly dividing the search interval in half
  • Compare the target with the middle element of the array
  • If the target matches, return the index
  • If the target is less than the middle element, search the left half
  • If the target is greater than the middle element, search the right half
  • Base case for recursive version: empty search interval or target found
  • Handle edge cases like empty lists properly

Steps to solve by this approach:

 Step 1: If the search range is invalid (low > high), return -1 as base case.
 Step 2: Calculate the middle index as (low + high) // 2.
 Step 3: If the middle element equals the target, return its index.
 Step 4: If the middle element is less than the target, search recursively in the right half.
 Step 5: If the middle element is greater than the target, search recursively in the left half.

Submitted Code :