
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)
Editorial
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. |
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