/*write a c program to search given number into the list using binary
search method*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,pos=0,start=0,end,a[30],n,mid=0,num,flag=0,temp=0;
clrscr();
printf("\nenter how many number you want:-");
scanf("%d",&n);
printf("\nenter the number:-");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
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;
}
}
}
printf("\nthe array in sorted order:-\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("\nenter number for search:-");
scanf("%d",&num);
end=n;
while(start<=end)
{
mid=(start+end)/2;
if(a[mid]==num)
{
flag=1;
pos=mid+1;
break;
}
else
{
if(a[mid]<num)
start=mid+1;
else
end=mid-1;
}
}
if(flag==1)
printf("\nthe number is found at %d location",pos);
else
printf("\nnumber not found");
getch();
}
/*-----------------OUTPUT---------------
enter how many number you want:-5
enter the number:-6
9
8
7
4
the array in sorted order:-
4
6
7
8
9
enter number for search:-6
the number is found at 2 location
enter how many number you want:-4
enter the number:-7
8
4
1
the array in sorted order:-
1
4
7
8
enter number for search:-9
number not found
*/
No comments:
Post a Comment