F How We Can Do Binary search Operation On a Sorted Array? | CodeTheta

How We Can Do Binary search Operation On a Sorted Array?

May 10, 2014

This program is a binary search operation on a sorted array.Output of this program is in this picture.
 Try this code in your own machine and execute it.


/* http://native-code.blogspot.com */

#include<stdio.h>
#include<conio.h>
#define MAX 10

int binary_search(int[], int, int, int);

void main()
{
int a[MAX],x,max,i,lo=0;
x=max=0;
printf("/* http://native-code.blogspot.com */");
printf("\n Enter the length of the array:");
scanf("%d",&max);
printf("\n Enter the array elements:");
for(i=0;i<max;i++)
scanf("%d",&a[i]);
printf("\n The array before Search: \n");
for(i=0;i<max;i++)
printf("\t%d",a[i]);
printf("\n\n Enter the Element that you want to Search: ");
scanf("%d",&x);
i=binary_search(a,lo,max,x);
if(i==-1)
printf("\n Element not found.");
else
printf("\n Element found at %d position.",i+1);
getch();
}

int binary_search(int a[], int lo, int hi, int x)
{
int mid=(hi+lo)/2;
if(hi<lo)
{
printf("\nElement not found.");
return(-1);
}
else
{
if(a[mid]==x)
{
printf("\nElement found.");
return(mid);
}
else
{
if(x>a[mid])
{
lo=mid+1;
binary_search(a,lo,hi,x);
}
else
{
hi=mid-1;
binary_search(a,lo,hi,x);
}
}
}
}

/* http://native-code.blogspot.com */

Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us

Post a Comment

PRODUCTS

LISTS OF PRODUCTS

SERVICES

SKILLS
SOFTWARE DEVELOPMENT
WEBSITE DEVELOPMENT
WEB HOSTING
BULK SMS SERVICE
SEO SERVICE
ANDROID APPS
QR CODE / BARCODE
HARDWARE SERVICE
OUR WORK AREA