Binary Search
Binary Search
#include <stdio.h>
int binarySearch(int arr[], int size, int target)
{
int left = 0;
int right = size - 1;
if (arr[mid] == target)
{
return mid; // Element found, return its index
}
else if (arr[mid] < target)
{
left = mid + 1; // Search the right half
}
else
{
right = mid - 1; // Search the left half
}
}
main()
{
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 7;
getch();
}
if (*mid == target)
{
return mid - arr; // Element found, return its index
}
else if (*mid < target)
{
left = mid + 1; // Search the right half
}
else
{
right = mid - 1; // Search the left half
}
}
main()
{
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int result = binarySearch(arr, size, target);
clrscr();
if (result != -1)
{
printf("Element %d found at index %d\n", target, result);
}
else
{
printf("Element %d not found in the array\n", target);
}
getch();
}