Binary Search Program in C…!!!

As one of the basic searching technique we learned about Linear Search.Today we shall learn about Binary Search technique.In linear searching method we compared each element of the array with given key.The main drawback of the linear search is,”if the key present in the last position of the array then,number of steps to find the element is n”, where n is size of the array.For an array with size less than 10,does not matter.But for an array with size of 1000,the number of steps needed to search the element matter’s a lot.

The main essence of this method is…….just divide the entire array into parts comparing with middle value of the array.Let us consider an example…….Let the elements of the array be 1 2 3 4 5.The key to search in the array is 1.
Step 1: Sort the given array in ascending order(you can sort in any way)
Step 2: Compare the given key element with middle value of the array.
Step 3: If the element at middle is less than the key then consider the elements from starting to the middle of the array.
Step 4: If the element at middle is greater than the key then consider the elements from middle of the array to ending of the array
Step 5: Now repeat from step 2 to step 4 until you search the element.

The code for the above program is:

#include<stdio.h>
#include<conio.h>
int bsearch(int[],int,int);
int i;
void main()
 {
	int a[100],j,n,pos=-1,key;
	clrscr();
	printf("Enter array size");
	scanf("%d",&n);
	printf("Enter values into array");
	for(j=0;j<n;j++)
	 {
		scanf("%d",&a[j]);
	 }
	printf("Enter the value to be serached");
	scanf("%d",&key);
	pos=bsearch(a,key,n);
	if(pos==-1)
	 {
		printf("Unsucess full");
	 }
	else
	 {
		printf("sucess full");
		printf("the element is found at %d",pos);
	 }
	getch();
 }
int bsearch(int a[],int key,int n)
{
	int first=0,last=n-1,middle;
	while(last>=first)
	 {
	 	middle=(first+last)/2;
		if(key<a[middle])
			last=middle-1;
		else if(key>a[middle])
			first=middle+1;
		else
			return middle;
	}
    return -1;
}


OUTPUT:
bsearch
To download the program click here:download

Advertisements

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my Master's in Computer Science.
This entry was posted in C and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s