PROGRAM TO FIND AN ELEMENT USING BINARY SEARCH

//TO FIND AN ELEMENT USING BINARY SEARCH//
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,k,ptr,lb,ub,beg,end,mid,loc,item,temp,A[10];
clrscr();
printf(“Enter the total number of elements of the array: “);
scanf(“%d”,&n);
printf(“Enter the elements in the array:\n”);
for(i=1;i<=n;i++)
{
printf(“Element number [%d] is “,i);
scanf(“%d”,&A[i]);
}
//SORTING THE ARRAY//
for(k=1;k<=n-1;k++)
{
ptr=1;
while(ptr<=n-k)
{
if(A[ptr]>A[ptr+1])
{
temp=A[ptr];
A[ptr]=A[ptr+1];
A[ptr+1]=temp;
}
ptr=ptr+1;
}
}       //SORTING ENDS//
printf(“Sorted array is:\n”);
for(i=1;i<=n;i++)
{
printf(“Element number [%d] is %d\n”,i,A[i]);
}
printf(“Enter the element which you want to search: “);
scanf(“%d”,&item);
//SEARCHING BEGINS//
lb=1;
ub=n;
beg=lb;
end=ub;
mid=(beg+end)/2;
while((beg<=end) && (A[mid]!=item))
{
if(item<A[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
mid=(beg+end)/2;
}
if(A[mid]==item)
{
loc=mid;
printf(“Element is present at [%d] location”,loc);
}
else
printf(“Element is not present in the given array”);
getch();
}

Leave a Reply

Your email address will not be published. Required fields are marked *