C Program Code to Perform Binary Search using function


Algorithm:-

1.Start
2.Accept size of array and input the elements
3.Perform sorting operation  //For sorting
4.Display the sorted array    //http://crazyfactzz.blogspot.in/2016/01/c-program-code-for-selection-sort.html
5.Goto step 7 (calling the function)
6.Stop
7.Accept the element to be searched
8.Check whether h<l where h=0,l=n-1,p=-1
   if yes goto step 9 else step 13
9.m=(l+h)/2
10.Check whether a[m]==num
     If yes assign the value as,p=m else goto step 11
11.Check whether a[m]<num
    If yes then h=m+1, else h=m-1
12.Return to step 8
13.Return to step 6
14.Check whether p|=-1
     Yes,Display the number is found at p+1 position
     Else,Display the number is not in array
15.Goto step 6
  
Program:-

/*Program to perform binary search - Crazy Factzz */
#include<stdio.h>
#include<conio.h>
void search (int [],int,int);

void main()
{
clrscr();
int n,i,a[100],num;
printf("\n Enter the Array limit : ");
scanf("%d",&n);
printf("\n Enter the array elements \n");
for(1=0;1<n;i++)
scanf("%d",&a[i]);
printf ("\n ENTER THE NUMBER TO BE SEARCHED  : ");
scanf ("%d", &num);
search (a,n, num);
getch();
}

void search (int a[] ,int n, int num)
{
int p=-1,l=n-1, h=0, m=(l+h) /2;
while (h<l)
{
if (a[m] ==num)
{
p=m;
break:
}
else if (a[m]>num)
{
l=m-1;
m=(h+1)/2;
}
else
{
h=m+1:
m=(h+1)/2;
}
}
if (p!=-1)
printf ("\n THE NUMBER IS FOUND AT %d POSITION ",p+1);
else
printf ("In NOT FOUND");
}

For more C programs - click here

Popular posts from this blog

8051 Assembly Program Code for Sorting in Descending Order - Keil - AT89C51

8051 Assembly Program Code for Sorting in Ascending Order - Keil -AT89C51