Search Your Query

Breaking

Tuesday, July 9, 2019

Binary Searching


Binary Searching

Program Code:

#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,i,j,n,k,mid,beg,end,temp;
printf("Enter the size of the array\n");
scanf("%d",&n);
a=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
printf("Enter the %d element\n",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
{
printf("The sorted array is-->%d\n",a[i]);
}
beg=0;
end=n-1;
printf("Enter the number that you searched\n");
scanf("%d",&k);
mid=(beg+end)/2;
while(beg<=end && k!=a[mid])
{
if(k<a[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
mid=(beg+end)/2;
}
if(k==a[mid])
{
printf("Your Number is found\n");
}
else
{
printf("Your number is not found\n");
}
return 0;

}

Hence, //coming soon

Input:

Enter the size of the array
5
Enter the 1 element
65
Enter the 2 element
54
Enter the 3 element
32
Enter the 4 element
14
Enter the 5 element
74
The sorted array is-->14
The sorted array is-->32
The sorted array is-->54
The sorted array is-->65
The sorted array is-->74
Enter the number that you searched
78

Output:

Your number is not found

Input:

Enter the size of the array
5
Enter the 1 element
65
Enter the 2 element
54
Enter the 3 element
32
Enter the 4 element
14
Enter the 5 element
74
The sorted array is-->14
The sorted array is-->32
The sorted array is-->54
The sorted array is-->65
The sorted array is-->74
Enter the number that you searched
54

Output:

Your Number is found




No comments:

Post a Comment