Binary search using c

Leave a Comment
#include<conio.h>
#include<stdio.h>
int main()
{
int a[100],n,loc=-1,s,i,j,t,mid,first,last;
printf("Enter The Max limit:");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nEnter the number:");
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++){
for(j=i+1;j<n;j++) {
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf("\nThe sorted array is\n");
for(i=0;i<n;i++){
printf("%d\t",a[i]);
}
printf("\nEnter the search element:");
scanf("%d",&s);
first=0;last=n-1;
while((loc==-1)&&(first<=last))
{
mid=(first+last)/2;
if(a[mid]==s)
{
loc=mid;
break;
}
else if(s>a[mid])
{
first=mid+1;
}
else if(s {
last=mid-1;
}
}
if(loc==-1)
printf("\nThe element entered is not found in the array!");
else
printf("\nThe number u entered is found on the list at position %d",loc+1);
getche();
return 0;
}

0 comments: