0% found this document useful (0 votes)
9 views

Binary Operator

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Binary Operator

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

/* Write C programs that use both recursive and non recursive functions to perform

The following searching operations for a Key value in a given list of integers :
ii) Binary search*/
#include <stdio.h>
#define MAX_LEN 10
/* Non-Recursive function*/
Void b_search_nonrecursive(int l[],int num,int ele)
{
Int l1,I,j, flag = 0;
L1 = 0;
I = num-1;
While(l1 <= i)
{
J = (l1+i)/2;
If( l[j] == ele)
{
Printf(“\nThe element %d is present at position %d in list\n”,ele,j);
Flag =1;
Break;
}
Else
If(l[j] < ele)
L1 = j+1;
Else
I = j-1;
}
If( flag == 0)
Printf(“\nThe element %d is not present in the list\n”,ele);
}
/* Recursive function*/
Int b_search_recursive(int l[],int arrayStart,int arrayEnd,int a)
{
Int m,pos;
If (arrayStart<=arrayEnd)
{
M=(arrayStart+arrayEnd)/2;
If (l[m]==a)
Return m;
Else if (a<l[m])
Return b_search_recursive(l,arrayStart,m-1,a);
Else
Return b_search_recursive(l,m+1,arrayEnd,a);
}
Return -1;
}

Void read_list(int l[],int n)


{
Int I;
Printf(“\nEnter the elements:\n”);
For(i=0;i<n;i++)
Scanf(“%d”,&l[i]);
}
Void print_list(int l[],int n)
{
Int I;
For(i=0;i<n;i++)
Printf(“%d\t”,l[i]);
}
/*main function*/
Void main()
{
Int l[MAX_LEN], num, ele,f,l1,a;
Int ch,pos;
Clrscr();
Printf(“======================================================”);
Printf(“\n\t\t\tMENU”);
Printf(“\n=====================================================”);
Printf(“\n[1] Binary Search using Recursion method”);
Printf(“\n[2] Binary Search using Non-Recursion method”);
Printf(“\n\nEnter your Choice:”);
Scanf(“%d”,&ch);
If(ch<=2 & ch>0)
{
Printf(“\nEnter the number of elements : “);
Scanf(“%d”,&num);
Read_list(l,num);
Printf(“\nElements present in the list are:\n\n”);
Print_list(l,num);
Printf(“\n\nEnter the element you want to search:\n\n”);
Scanf(“%d”,&ele);
Switch(ch)
{
Case 1:printf(“\nRecursive method:\n”);
Pos=b_search_recursive(l,0,num,ele);
If(pos==-1)
{
Printf(“Element is not found”);
}
Else
{
Printf(“Element is found at %d position”,pos);
}
Getch();
Break;
Case 2:printf(“\nNon-Recursive method:\n”);
B_search_nonrecursive(l,num,ele);
Getch();
Break;
}
}
Getch();
}

You might also like