To search given element in sorted array using binary search method.
#include
#include
main()
{
int a[100],n,i,ITEM,MID,LB,UB,found=0;
clrscr();
printf("Enter number of nodes in array ");
scanf("%d",&n);
for(i=0;i{
printf("Input INFORMATION at NODE %d",i+1);
scanf("%d",&a[i]);
}
printf("Enter element to be searched : ");
scanf("%d",&ITEM);
LB=0;
UB=n-1;
MID=(LB+UB)/2;
while(LB<=UB)
{
if(a[MID]==ITEM)
found=MID;
if(a[MID]>ITEM)
UB=MID-1;
else
LB=MID+1;
MID=(LB+UB)/2;
}
if(found==0)
printf("\nThe element is not present ");
else
printf("\nElement found at position %d",found+1);
getch();
}
No comments:
Post a Comment