Binary Search
/*******************************************************************************/
#include <stdio.h>
int binarySearch(int arr[], int n, int target) {
int left=0,right=n-1,mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Target found, return its index
}
if (arr[mid] < target) {
left = mid + 1; // Target is in the right half
} else {
right = mid - 1; // Target is in the left half
}
}
return -1; // Target not found
}
int main() {
int i,n,arr[50],target,result;
printf("Enter number of elements :: ");
scanf("%d",&n);
printf("\nEnter %d elements in sorted order:: \n", n);
for ( i = 0 ; i < n ; i++ )
{
scanf("%d",&arr[i]);
}
printf("\nEnter key value to search :: ");
scanf("%d",&target);
result = binarySearch(arr, n, 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;
}
/*******************************************************************************/
/* Recursive Implementation of Binary Search */
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
if (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Target found, return its index
}
if (arr[mid] < target) {
return binarySearch(arr, mid + 1, right, target); // Search in the right half
} else {
return binarySearch(arr, left, mid - 1, target); // Search in the left half
}
}
return -1; // Target not found
}
int main() {
int i,n,arr[50],target,result;
printf("Enter number of elements :: ");
scanf("%d",&n);
printf("\nEnter %d elements in sorted order:: \n", n);
for ( i = 0 ; i < n ; i++ )
{
scanf("%d",&arr[i]);
}
printf("\nEnter key value to search :: ");
scanf("%d",&target);
result = binarySearch(arr, 0,n-1, 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;
}
Comments
Post a Comment