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:

int bsearch(int[],int,int);
int i;
void main()
	int a[100],j,n,pos=-1,key;
	printf("Enter array size");
	printf("Enter values into array");
	printf("Enter the value to be serached");
		printf("Unsucess full");
		printf("sucess full");
		printf("the element is found at %d",pos);
int bsearch(int a[],int key,int n)
	int first=0,last=n-1,middle;
		else if(key>a[middle])
			return middle;
    return -1;

To download the program click here:download


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 PhD 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: Logo

You are commenting using your 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