
Problem
Solution
Submissions
Binary Search
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program that implements the binary search algorithm. The program should take a sorted array of integers and a target value as input, and return the index of the target value in the array. If the target value is not found, return -1.
Example 1
- Input:
- array = [1, 3, 5, 7, 9, 11, 13]
- target = 7
- Output: 3
- Explanation:
- Step 1: Initialize low = 0 and high = 6 (array length - 1).
- Step 2: Calculate mid = (low + high) / 2 = 3.
- Step 3: Compare array[mid] = 7 with target = 7. They are equal.
- Step 4: Return mid = 3 as the index of the target element.
Example 2
- Input:
- array = [2, 4, 6, 8, 10]
- target = 5
- Output: -1
- Explanation:
- Step 1: Initialize low = 0 and high = 4 (array length - 1).
- Step 2: Calculate mid = (low + high) / 2 = 2.
- Step 3: Compare array[mid] = 6 with target = 5. array[mid] > target.
- Step 4: Set high = mid - 1 = 1.
- Step 5: Calculate mid = (low + high) / 2 = 0.
- Step 6: Compare array[mid] = 2 with target = 5. array[mid] < target.
- Step 7: Set low = mid + 1 = 1.
- Step 8: Calculate mid = (low + high) / 2 = 1.
- Step 9: Compare array[mid] = 4 with target = 5. array[mid] < target.
- Step 10: Set low = mid + 1 = 2.
- Step 11: Now low > high, so target is not found.
- Step 12: Return -1.
Constraints
- 1 ≤ array.length ≤ 10^6
- The array is sorted in ascending order
- -10^9 ≤ array[i] ≤ 10^9
- Time Complexity: O(log n), where n is the length of the array
- 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
- Use two pointers (left and right) to keep track of the search range.
- Calculate the middle index and compare the middle element with the target value.
- If the middle element is equal to the target, return the middle 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.
- Repeat the process until the target is found or the search range is empty.