To find the element 80 in the sorted array using the binary search algorithm, you can follow these steps:
1. Initialize two pointers, `low` and `high`, to the first and last indices of the array, respectively. In this case, `low = 0` and `high = 12` (since the array has 13 elements).
2. Calculate the middle index: `mid = (low + high) / 2`, which in this case is `mid = (0 + 12) / 2 = 6`.
3. Compare the element at the middle index, `data[mid]`, with the target value, 80.
– `data[6]` is 55, which is less than 80.
4. Since 55 is less than 80, you know that the target value (80) must be to the right of the middle element.
5. Update the `low` pointer to `mid + 1`, so `low = 7`, and repeat the process.
6. Calculate the new middle index: `mid = (low + high) / 2`, which is `mid = (7 + 12) / 2 = 9`.
7. Compare `data[9]` (which is 77) with the target value (80).
8. Since 77 is less than 80, again, you know that the target value (80) must be to the right of the middle element.
9. Update the `low` pointer to `mid + 1`, so `low = 10`, and repeat the process.
10. Calculate the new middle index: `mid = (low + high) / 2`, which is `mid = (10 + 12) / 2 = 11`.
11. Compare `data[11]` (which is 88) with the target value (80).
12. Since 88 is greater than 80, you know that the target value (80) must be to the left of the middle element.
13. Update the `high` pointer to `mid – 1`, so `high = 10`.
14. Repeat the process with the new values of `low` and `high`.
15. Calculate the new middle index: `mid = (low + high) / 2`, which is `mid = (10 + 10) / 2 = 10`.
16. Compare `data[10]` (which is 80) with the target value (80).
17. Since they are equal, you have found the target value (80).
It took a total of 4 passes to find the element 80 using the binary search algorithm in this sorted array.
#include
int binarySearch(int arr[], int size, int target) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Calculate the middle index
if (arr[mid] == target) {
return mid; // Element found, return its index
} else if (arr[mid] < target) {
low = mid + 1; // Target is in the right half
} else {
high = mid - 1; // Target is in the left half
}
}
return -1; // Element not found
}
int main() {
int data[] = {11, 22, 30, 33, 40, 44, 55, 60, 66, 77, 80, 88, 99};
int target = 80;
int size = sizeof(data) / sizeof(data[0]);
int result = binarySearch(data, size, target);
if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}
return 0;
}