Recursive binary search in C.

 

01 #include<stdio.h>
02
03 int main()
04 {
05 int a[10],i,n,m,c,l,u;
06 printf("Enter the size of an array: ");
07 scanf("%d",&n);
08 printf("Enter the elements of the array: " );
09
10 for(i=0; i<n; i++)
11 {
12 scanf("%d",&a[i]);
13 }
14 printf("Enter the number to be search: ");
15 scanf("%d",&m);
16 l=0,u=n-1;
17 c=binary(a,n,m,l,u);
18
19 if(c==0)
20 printf("Number is not found.");
21 else
22 printf("Number is found.");
23 return 0;
24 }
25 int binary(int a[],int n,int m,int l,int u)
26 {
27 int mid,c=0;
28 if(l<=u)
29 {
30 mid=(l+u)/2;
31 if(m==a[mid])
32 {
33 c=1;
34 }
35 else if(m<a[mid])
36 {
37 return binary(a,n,m,l,mid-1);
38 }
39 else
40 return binary(a,n,m,mid+1,u);
41 }
42 else
43 return c;
44 }
 
 OUTPUT :

(1st Run )
Enter the size of an array: 5
Enter the elements of the array:
12
32
11
45
44

Enter the number to be search: 45

Number is found.

(2nd Run )

Enter the size of an array: 5
Enter the elements of the array:
12
32
11
45
44

Enter the number to be search: 30

Number is not found.

Related Post

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.