Skip to main content

Binary Search Using Function in C

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

void sorting(int DATA[50],int x);
void find_location(int DATA[50],int x);
void read_value(int DATA[50],int x)
	{
	int i;
		//READING VALUE//
	for(i=1;i<=x;i++)
		{
		printf("DATA[%d]=",i);	scanf("%d",&DATA[i]);
		}
	sorting(DATA,x);
	}
void sorting(int DATA[50],int x)
	{
	int i,j,t;
		//START SORTING//
	for(i=1;i<=x-1;i++)
		{
		for(j=i+1;j<=x;j++)
			{
			if(DATA[i]>DATA[j])
				{
				t=DATA[i];
				DATA[i]=DATA[j];
				DATA[j]=t;
				}
			}
		}
	printf("AFTER SORTING..\n");
	for(i=1;i<=x;i++)
		{
		printf("\nDATA[%d]=%d",i,DATA[i]);
		}
	find_location(DATA,x);
	}
void find_location(int DATA[50],int x)
	{
	int v,beg,end,mid;
	printf("\nENTER VALUE TO FIND:\t"); scanf("%d",&v);
	beg=1;	end=x; 	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");
		}
	}
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);
	read_value(DATA,n);
	BINARY_SEARCH:
	find_location(DATA,n);
	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 *