Binary search is an efficient algorithm for finding an element within a sorted array
Binary search is an efficient algorithm for finding an element within a sorted array
1. Initialize two pointers: `left` at the start (index 0) and `right` at the end (index 9) of the array.
2. Calculate the middle index: `middle = left + (right - left) / 2`. In the first iteration, `middle = 0 + (9 - 0) /
2 = 4`.
- If `arr[middle]` is less than the target, set `left = middle + 1` and repeat from step 2.
- If `arr[middle]` is greater than the target, set `right = middle - 1` and repeat from step 2.
- Initial array: `{2, 5, 8, 12, 16, 23, 38, 56, 72, 91}`
- Target: `23`
2. Calculate `middle = 0 + (9 - 0) / 2 = 4`
4. Calculate `middle = 5 + (9 - 5) / 2 = 7`
6. Calculate `middle = 5 + (6 - 5) / 2 = 5`
Thus, the target element `23` is found at index `5` in the array.
Would you like a code snippet to implement this in a specific programming language?
#include <iostream>
if (arr[middle] == target)
return middle;
left = middle + 1;
else
right = middle - 1;
return -1;
int main() {
int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
cout << "Element found at index " << result << endl;
else
return 0;