Binary Search
      It is a search method for searching numbers etc. in an array etc. But binary search can take place in an array that is already sorted in increasing or decreasing order (or any order like alphabetical order etc.).
/* binary search*/

#include<conio.h>
#include<stdio.h>

int a[6],x;

int binarysearch(int low, int high)
{
	int mid;

	if(low>high)
	{
		printf("\nsince %d>%d therefore value not found",low,high);
		return(-1);
	}
	printf("\nlow=%d is smaller than high=%d\n%d<%d",low,high,low,high);
	mid = (low+high)/2;
	printf("\n the value of mid is (%d+%d)/2 = %d",low,high,mid);
	if(x==a[mid])
	{
		printf("\nthe value is found %d=%d",x,mid);

		return mid;
	}
	else
	{
		if(x<a[mid])
		{
			printf("\nsince the value at x mid=%d is %d and %d<%d so if part",mid,a[mid],x,a[mid]);
			printf("\nnow search from low=%d to high=%d",low,mid-1);
			binarysearch(low,mid-1);
		}
		else
		{
			printf("\nsince the value at x mid=%d is %d and %d>%d so else part",mid,a[mid],x,a[mid]);
			printf("\nnow search from low=%d to high=%d",mid+1,high);
			binarysearch(mid+1,high);
		}
	}
}

void main()
{
	clrscr();
	printf("\na program implementing binary search");

	int result,i;
	printf("\ngive the values of an array give 6 numbers");
	for(i=0;i<6;i++)
	{
		scanf("%d",&a[i]);
	}
	printf("\nthe array to be searched is");
	for(i=0;i<6;i++)
	{
		printf(" %d",a[i]);
	}

	printf("\n enter the value to be searched :");
	scanf("%d",&x);

	result = binarysearch(0,i);
	if(result==-1)
		printf("\nvalue not found");
	else
		printf(" the value is found");

	getch();
}

									

Download Program
Did You Know ?
IP address is a numerical label that is assigned to devices participating in a computer network. Read More