Tutorialspoint
Problem
Solution
Submissions

Binary Search Implementation

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to implement the binary search algorithm. Binary search is an efficient algorithm for finding an element in a sorted array. The algorithm works by repeatedly dividing the search range in half until the target element is found or it is determined that the element does not exist in the array.

Example 1
  • Input: - nums = [1, 3, 5, 7, 9, 11, 13] - target = 7
  • Output: 3
  • Explanation: The value 7 is found at index 3 in the array.
Example 2
  • Input: - nums = [1, 3, 5, 7, 9, 11, 13] - target = 6
  • Output: -1
  • Explanation: The value 6 is not found in the array, so the function returns -1.
Constraints
  • 1 ≤ nums.length ≤ 10^6
  • -10^9 ≤ nums[i] ≤ 10^9
  • All the elements in the array are sorted in ascending order
  • -10^9 ≤ target ≤ 10^9
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsAccentureSnowflake
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

  • Ensure the array is sorted in ascending order
  • Initialize two pointers: left at the beginning and right at the end of the array
  • While left <= right, calculate the middle index
  • If the middle element equals the target, return its index
  • If the middle element is greater than the target, search in the left half
  • If the middle element is less than the target, search in the right half

Steps to solve by this approach:

 Step 1: Initialize two pointers, left = 0 and right = array length - 1.

 Step 2: While left pointer is less than or equal to right pointer, calculate the middle index.
 Step 3: Compare the middle element with the target value.  Step 4: If they are equal, return the middle index.
 Step 5: If the middle element is less than the target, update left = mid + 1 to search in the right half.
 Step 6: If the middle element is greater than the target, update right = mid - 1 to search in the left half.
 Step 7: If the while loop ends without finding the target, return -1 to indicate the target is not present in the array.

Submitted Code :