Search for key Element in an Array using Binary Search
#include<stdio.h>
void main()
{
int
a[100], i, n, low, high, mid, key;
printf("\nEnter value of
n: ");
scanf("%d", &n);
printf("\nEnter the array
elements: ");
for(i=0; i<n; i++)
scanf("%d",
&a[i]);
printf("\nEnter key: ");
scanf("%d", &key);
low = 0;
high = n-1;
while(low<=high)
{
mid =
(low+high)/2;
if(key == a[mid])
{
printf("\nKey
element is found at position = %d",mid+1);
break;
}
else if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
if(low>high)
printf("\nKey
is not found");
}
Output:
Case 1:
Enter value of n: 6
Enter the array elements: 11 22 33 44
55 66
Enter key: 55
Key element is found at position = 5
Case 2:
Enter value of n: 6
Enter the array elements: 11 22 33 44
55 66
Enter key: 88
Key
is not found