You are on page 1of 2

// Program for Binary Search.

// Created by Aakash Shukla.


#include<stdio.h>
int main()
{
printf("ENTR THE VALUE OF N : ");
int n,i,j,temp,left,right,mid,c,count;
scanf("%d",&n);
int a[n];
// now we will take input from user in an array
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
//now we will sort the array
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while(temp<a[j]&&j>=0)
{
a[j+1]=a[j];
a[j]=temp;
j=j-1;
}
}
printf("Enter the number for which you want to search in the array :");
scanf("%d",&c);
//now since array has been sorted. now we will do the binary search.
count=0;
left=0;
right=n-1;
while(left<=right)
{
mid=(left+right)/2;
if(a[mid]==c)
{
count=count+1;
temp=mid;
break;
}
else if(a[mid]>c)
{
right=mid-1;
mid=(left+right)/2;
}
else if(a[mid]<c)
{
left=mid+1;
mid=(left+right)/2;
}
}
if(count==1)
{
printf("%d is in the array and its position in sorted array is
%d\n",c,temp+1);
}
else
{
printf("%d is not in the array\n",c);
}

You might also like