binary search
#include <stdio.h>
int main() {
int arr[] = {5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 30;
int low = 0;
int high = size - 1;
int mid;
int index = -1;
while (low <= high) {
mid = low + (high - low) / 2;
// Check if the target is exactly the middle element
if (arr[mid] == target) {
index = mid;
break;
}
// If the target is greater than the middle element, ignore the left half
if (arr[mid] < target) {
low = mid + 1;
}
// If the target is less than the middle element, ignore the right half
else {
high = mid - 1;
}
}
if (index != -1) {
printf("Element %d found at index %d", target,index);
} else {
printf("Not found");
}
return 0;
}
Comments
Post a Comment