Write a c program to perform binary search
#include <stdio.h>
// Function to perform binary search
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if the target is present at mid
if (arr[mid] == target) {
return mid;
}
// If target is greater, ignore the left half
if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
}
}
// Target is not present in the array
return -1;
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n, target;
// Input the number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
// Input the elements of the array
printf("Enter the elements (sorted in ascending order): ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input the target value to search for
printf("Enter the target value: ");
scanf("%d", &target);
// Perform binary search
int result = binarySearch(arr, 0, n - 1, target);
// Print the result
if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found in the array.\n");
}
return 0;
}
Comments
Post a Comment