/*program to implement binary search*/
#include<stdio.h>
void sort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int binsearch(int a[],int n)
{
int item,beg,mid,end,i;
printf("the sorted list is\n");
sort(a,n);
for(i=0;i<n;i++)
printf("%d",a[i]);
printf("\n");
printf("enter the element to be searched:");
scanf("%d",&item);
beg=0;
end=n;
while(beg<=end)
{
mid=(beg+end)/2;
if(a[mid]==item)
return mid+1;
else if (a[mid]<item)
beg=mid+1;
else
end=mid-1;
}
}
main()
{
int a[20],i,size,loc;
printf("enter the size of the array");
scanf("%d",&size);
printf("enter the elements");
for(i=0;i<size;i++)
scanf("%d",&a[i]);
loc=binsearch(a,size);
if(loc==0)
printf("element is not found");
else
printf("element is found at the location:%d",loc);
}
...........................OUTPUT.............
enter the size of the array
5
enter the elements
1
9
5
7
6
the sorted list is
15679
enter the element to be searched:.6
element is not found
enter the size of the array
5
enter the elements
9
4
6
7
1
the sorted list is
14679
enter the element to be searched:6
element is found at the location:3
#include<stdio.h>
void sort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int binsearch(int a[],int n)
{
int item,beg,mid,end,i;
printf("the sorted list is\n");
sort(a,n);
for(i=0;i<n;i++)
printf("%d",a[i]);
printf("\n");
printf("enter the element to be searched:");
scanf("%d",&item);
beg=0;
end=n;
while(beg<=end)
{
mid=(beg+end)/2;
if(a[mid]==item)
return mid+1;
else if (a[mid]<item)
beg=mid+1;
else
end=mid-1;
}
}
main()
{
int a[20],i,size,loc;
printf("enter the size of the array");
scanf("%d",&size);
printf("enter the elements");
for(i=0;i<size;i++)
scanf("%d",&a[i]);
loc=binsearch(a,size);
if(loc==0)
printf("element is not found");
else
printf("element is found at the location:%d",loc);
}
...........................OUTPUT.............
enter the size of the array
5
enter the elements
1
9
5
7
6
the sorted list is
15679
enter the element to be searched:.6
element is not found
enter the size of the array
5
enter the elements
9
4
6
7
1
the sorted list is
14679
enter the element to be searched:6
element is found at the location:3
No comments:
Post a Comment