Advertisement

C PROGRAM FOR BINARY SEARCH

#include<stdio.h>
#include<conio.h>
void main()
{
int array[10];
int i, j, n, temp, num;
int low,mid,high;
clrscr();
printf("Enter the value of the array\t");
scanf("%d",&n);
printf("Enter the elements one by one:\n");
for(i=0;i<n;i++)
{
scanf("%d",&array[i]);
}
printf("Input array elements\n");
for(i=0;i<n;i++)
{
printf("%d\n",array[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<(n-i-1);j++)
{
if(array[j]>array[j+1])
{
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
printf("Sorted array is...\n");
for(i=0;i<n;i++)
{
printf("%d\n",array[i]);
}
printf("Enter the element to be searched\n");
scanf("%d",&num);
low=1;
high=n;
do
{
mid=(low+high)/2;
if(num<array[mid])
high=mid-1;
else if(num>array[mid])
low=mid+1;
}
while(num!=array[mid] && low<=high);
if(num==array[mid])
{
printf("\n\tis present at position %d",array[i],i+1);
}
else
{
printf("Search is FAILED\n");
}
getch();
}

No comments:

Post a Comment

Please comment bellow. Share your knowledge