/* ****************************************************
26. TO SEARCH ELEMENT USING BINARY SEARCH .
**************************************************** */
#include<*stdio.h>
#include<*conio.h>
void main()
{
int a[10],n,i,mid,key,low,high,flag;
flag=1;
clrscr();
printf("\n enter the total number of elements : ");
scanf("%d",&n);
printf("\n enter sorted elements only : ");
for(i=0;i
{
scanf("%d",&a[i]);
}
printf("\n enter key element to be serched : ");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high&&flag==1)
{
mid=(low+high)/2;
if(key
high=mid-1;
else if(key>a[mid])
low=mid+1;
else
{
if(key==a[mid])
printf("\nelement found at position : %d ",mid+1);
flag=0;
}
}
if(flag)
{
printf("\n element not found ");
}
else
{
("\n search succesful");
}
getch();
}
output
enter the total number of elements : 5
enter sorted elements only : 1 2 3 4 5
enter key element to be serched : 5
element is foud at position : 5
enter the total number of elements : 5
enter sorted elements only : 1 2 3 4 5
enter key element to be serched : 6
element is not found
26. TO SEARCH ELEMENT USING BINARY SEARCH .
**************************************************** */
#include<*stdio.h>
#include<*conio.h>
void main()
{
int a[10],n,i,mid,key,low,high,flag;
flag=1;
clrscr();
printf("\n enter the total number of elements : ");
scanf("%d",&n);
printf("\n enter sorted elements only : ");
for(i=0;i
{
scanf("%d",&a[i]);
}
printf("\n enter key element to be serched : ");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high&&flag==1)
{
mid=(low+high)/2;
if(key
high=mid-1;
else if(key>a[mid])
low=mid+1;
else
{
if(key==a[mid])
printf("\nelement found at position : %d ",mid+1);
flag=0;
}
}
if(flag)
{
printf("\n element not found ");
}
else
{
("\n search succesful");
}
getch();
}
output
enter the total number of elements : 5
enter sorted elements only : 1 2 3 4 5
enter key element to be serched : 5
element is foud at position : 5
enter the total number of elements : 5
enter sorted elements only : 1 2 3 4 5
enter key element to be serched : 6
element is not found
0 comments:
Post a Comment