Skip to main content

Binary Search in C

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

void main()
	{
	clrscr();
	int i,t,j,n,beg,end,mid,DATA[50],loc,v;
	char c;
	printf("HOW MANY ELEMENT YOU WANT:\t"); scanf("%d",&n);
		//READING VALUE//
	for(i=1;i<=n;i++)
		{
		printf("DATA[%d]=",i); scanf("%d",&DATA[i]);
		}
		//START SORTING//
	for(i=1;i<=n-1;i++)
		{
		for(j=i+1;j<=n;j++)
			{
			if(DATA[i]>DATA[j])
				{
				t=DATA[i];
				DATA[i]=DATA[j];
				DATA[j]=t;
				}
			}
		}
	printf("AFTER SORTING..\n");
	for(i=1;i<=n;i++)
		{
		printf("\nDATA[%d]=%d",i,DATA[i]);
		}
	BINARY_SEARCH:
	printf("\nENTER VALUE TO FIND:\t"); scanf("%d",&v);
	beg=1;	end=n;	mid=(beg+end)/2;
	while(DATA[mid]!=v && beg<=end)
		{
		if(v>DATA[mid])
			{
			beg=mid+1;
			}
		else
			{
			end=mid-1;
			}
		mid=(beg+end)/2;
		}
	if(DATA[mid]==v)
		{
		printf("\n%d IS AT LOCATION %d",v,mid);
		}
	else
		{
		printf("\n\aLOCATION IS NOT FIND");
		}
	printf("\nTRY AGAIN ? (Y/N)..");
	c=getch();
	if(c=='y'||c=='Y')
		{
		goto BINARY_SEARCH;
		}
	else
		exit(0);
	}
Spread the love

Mashkawat Ahsan

I am Mashkawat Ahsan. Wikipedian, Mozillian, tech activist, art lover. Thank you for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *