## Sunday, September 4, 2011

### C program for Binary Search

`Hello, Today I am sharing how to implement Binary Search in C Programming `
`language. Here is the basic algorithm for binary search:`

C program for binary search :

#include<stdio.h>

int main(){
int a[8];
int i,x,first,last,mid;

printf("\nEnter 8 sorted elements like
[2 4 7 9 12 13 16 20]");
for(i=0;i<8;i++)
{
scanf("%d",&a[i]);
}
printf("\nYou entered following numbers:");
for(i=0;i<8;i++){
printf(" %d",a[i]);
}
printf("\nEnter the number you want to search: ");
scanf("%d",&x);

first=0,last=n-1;
while(first<=last){
mid=(first+last)/2;

if(x==a[mid]){
printf("\nThe number is found at %d", mid);
return 0;
}
else if(x<a[mid]){
last=mid-1;
}
else
first=mid+1;
}

printf("\nThe number is not in the list");

return 0;

}

I hope you this post is helpful for you. Thanks for reading.

icernn said...

hey u set last=n-1
but u havnt defined what n is
n can u please explain the logic used here

icernn said...

#include
#include
#include

int main()
{
int a[8];
int i,x,first,last,mid;

printf("\nEnter 8 sorted elements like [2 4 7 9 12 13 16 20] : ");
for(i=0;i<8;i++)
scanf("%d",&a[i]);

printf("\nYou entered following numbers: ");
for(i=0;i<8;i++)
printf(" %d",a[i]);

printf("\nEnter the number you want to search: ");
scanf("%d",&x);

first=1,last=8;
while(first<=last)
{
mid=(first+last)/2;

if(x==a[mid])
{
printf("\nThe number is found at %d", mid+1);
return 0;
}

else { if(x<a[mid])

last=mid-1;

else
first=mid+1;
}
}

printf("\nThe number is not in the list");

return 0;

}

this works if the list has to be in assending order.btw thanks for the codes dude

Jennifer said...