0% found this document useful (0 votes)
4 views

Binary Search

Uploaded by

Haaris Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Binary Search

Uploaded by

Haaris Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <stdio.

h>

int binarySearch(int arr[], int begin, int end, int target)


{
while (begin <= end)
{
int mid = (begin + end) / 2;

// Check if target is present at mid


if (arr[mid] == target)
return mid;
// If target greater, ignore begin half
else if (arr[mid] < target)
begin = mid + 1;
// If target is smaller, ignore end half
else
end = mid - 1;
}

// If we reach here, then the element was not present


return -1;
}

int main()
{
int arr[5];
printf("Enter 5 elements: ");
for (int i = 0; i < 5; i++)
{
scanf("%d", &arr[i]);
}
int n = sizeof(arr) / sizeof(arr[0]);
int target;
printf("Enter the search element: ");
scanf("%d", &target);

int result = binarySearch(arr, 0, n - 1, target);

if (result == -1)
printf("Element is not present in array\n");
else
printf("Element is present at index %d\n", result);

return 0;
}

You might also like