Binary Search in C Programming
#include<stdio.h>
main()
{
int low, high, middle, i, item, n, a[20];
//enter the element to be searched
printf("\nEnter the element to search : ");
scanf("%d",&item);
//enter the length of array (<=20)
printf("\nEnter the length of array : ");
scanf("%d",&n);
//enter the array elements
printf("\nEnter the elements for array.\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
low=1;
high=n;
do
{
middle=(low+high)/2;
if (item<a[middle])
{
high=middle-1;
}
if (item>a[middle])
{
low=middle+1;
}
} while (item!=a[middle] && (low<=high));
//print the result
if (item==a[middle])
printf("%d is found at position %d",item,middle);
else
printf("\nItem not found in given array.");
getch();
}
Comments
Post a Comment