Вы находитесь на странице: 1из 3

14.

Write recursive C Program for


a. Searching an element on a given list of integers using the
Binary Search methos.
b. Solving the Tower of Hanoi problem

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<process.h>
int search(int,int [],int,int);
void towers(int,char,char,char);
static int count=0;
int n1;
void main()
{
int choice;
int a[25],n,key,low,high,i,ans;
clrscr();
printf("Enter the choice:1.binary search 2.tower of hanoi\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Enter the array size:\n");
scanf("%d",&n);
printf("Enter the array elements:\n");
for(i=0;i<=(n-1);i++)
{
scanf("%d",&a[i]);
}
printf("Enter the key to be searched:\n");
scanf("%d",&key);
ans=search(key,a,0,n-1);
if(ans==1)
{
printf("Key found\n");
}
else
{
printf("Key not found\n");
}
break;
case 2:printf("enter n:\n");
scanf("%d",&n1);
towers(n1,'A','C','B');
break;
default:printf("Invalid choice\n");
break;
}
}
int search(int key,int a[],int low,int high)
{
int mid;
if(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
return(1);
}
if(key<a[mid])
{
return(search(key,a,low,mid-1));
}
else
{
return(search(key,a,mid+1,high));
}
}
return(-1);
}
void towers(int n1,char source,char dest,char aux)
{
if(n1==1)
{
printf("step%d:move%d from %c to %c\n",++count,n1,source,dest);
}
else
{
towers(n1-1,source,aux,dest);
printf("step%d:move%d from %c to %c\n",++count,n1,source,dest);
towers(n1-1,aux,dest,source);
}
}

OUTPUT

Enter the choice:1.binary search 2.tower of hanoi


1
Enter the array size:
4
10
20
30
40
Enter the key to be searched:
25
Key not found
Enter the choice:1.binary search 2.tower of hanoi
1
Enter the array size:
4
10
20
30
40
Enter the key to be searched:
20
key found
Enter the choice:1.binary search 2.tower of hanoi
2
enter n:
4
step1:move1 fromA to B
step2:move2 fromA to C
step3:move1 fromB to C
step4:move3 fromA to B
step5:move1 fromC to A
step6:move2 fromC to B
step7:move1 fromA to B
step8:move4 fromA to C
step9:move1 fromB to C
step10:move2 fromB to A
step11:move1 fromC to A
step12:move3 fromB to C
step13:move1 fromA to B
step14:move2 fromA to C
step15:move1 fromB to C

Вам также может понравиться