Tutorialspoint
Problem
Solution
Submissions

Binary Search

Certification: Basic Level Accuracy: 71.43% Submissions: 7 Points: 5

Write a Java program to implement binary search algorithm. Binary search is an efficient algorithm for finding an element in a sorted array. The function should return the index of the target element if found, otherwise return -1.

Example 1
  • Input: nums = [1, 3, 5, 7, 9, 11], target = 5
  • Output: 2
  • Explanation:
    • Mid = (0 + 5) / 2 = 2 → nums[2] = 5 → target found
Example 2
  • Input: nums = [1, 3, 5, 7, 9, 11], target = 6
  • Output: -1
  • Explanation:
    • Search reduces to empty range → target not found
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -10^4 ≤ nums[i] ≤ 10^4
  • All elements are unique and sorted
  • Time Complexity: O(log n)
  • Space Complexity: O(1) iterative, O(log n) recursive
ArraysAlgorithmsWalmart
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 only works on sorted arrays
  • Use two pointers (left and right) to track the search range
  • Calculate the middle element and compare it with the target
  • Adjust the search range based on the comparison
  • Can be implemented both iteratively and recursively

Steps to solve by this approach:

 Step 1: Initialize two pointers, left and right, to the start and end of the array.
 Step 2: Find the middle element by calculating mid = left + (right - left) / 2 to avoid integer overflow.
 Step 3: Compare the middle element with the target value.
 Step 4: If the middle element equals the target, return its index.
 Step 5: If the target is less than the middle element, search in the left half by updating right = mid - 1.
 Step 6: If the target is greater than the middle element, search in the right half by updating left = mid + 1.
 Step 7: Repeat steps 2-6 until left > right, at which point return -1 to indicate the target was not found.

Submitted Code :