You are on page 1of 24

UNIT I Recursion and Linear Search

Recursion and Linear Search

Preliminaries of algorithm:-

Definition: An algorithm is composed of a finite set of steps each of which may require one
or more operations. Every operation may be characterized as a either a simple or complex.

Or

An algorithm is an effective method expressed as a finite list of well defined instructions for
calculating a function.

An informal definition of algorithm is a set of rules that precisely defines a sequence of


operations.

Specifications or properties of algorithm:-

There are four specifications in which an algorithm has to follow

1. Definiteness 2.Effectiveness 3.Finiteness 4.Generality 5.Input/Output

(1) Definiteness: - Each step of algorithm must be precisely and unambiguously stated i.e.
each step of algorithm should be definite. e.g.: 5/0, here the division operation is not
possible which is not definite.
(2) Effectiveness: - Every step of algorithm must be effective i.e. every operation must be by
solved by pen and paper i.e. tracing of each step must be possible
(3) Finiteness: - Algorithm must terminate at a particular point. Every algorithm must be
terminated after performing some operation
(4) Generality: - An algorithm must be generic enough to solve all problems of a particular
class.
(5) Input-Output: - Usually the algorithm will have zero or more input quantities that are
given to it initially before the algorithm begins or during the run time dynamically. The
algorithm will have one or more output quantities which are dependent on input.

DS NEC, CSE Dept. Page 1


UNIT I Recursion and Linear Search

Development of an algorithm:-

Understand the problem


|
Decide on problem solving
|
Algorithm design technique
|
Prove correctness
|
Analyze the algorithm
|
Code the algorithm

Fig: steps in development of an algorithm

The following are the steps involved in developing an algorithm:

(1) Understand the problem: The first thing we need to do before designing an algorithm is to
understand the problem. We need to understand the basic functionality of the problem and its
usage.

(2) Problem solving: The problem can be solved based on the problem. It can be solved
exactly if possible or some approximations are made.

(3) Algorithm design technique: The algorithm can be designed by different techniques.
There are some techniques available for the development of algorithm.

1. Divide and conquer 2. Greedy method 3. Dynamic programming

(4) Prove correctness: An algorithm must prove its correctness for its approval.

(5) Analyze the algorithm: The algorithm can be analyzed based on two types

1. Time complexity 2. Space complexity

Of these two the time complexity is more important factor in analyzing the algorithm

The analysis of algorithm is done based on input to the algorithm. An algorithm can be best,
worst and average based on the type of the input we provide.

DS NEC, CSE Dept. Page 2


UNIT I Recursion and Linear Search

(6) Coding the algorithm: The algorithm implementation is final step in which an algorithm
can be coded, if it satisfies the above steps. The algorithm can be expressed in many kinds of
notation. Mostly the algorithms are intended to be implemented as computer programs.

Algorithms can be recursive and iterative.

Algorithm analysis and complexity:

An algorithm must not only be able to solve the problem. It must be able to do the
problem in an efficient manner. The algorithm efficiency can be determined by time
complexity and space complexity. Time complexity is major factor in determination of
algorithm efficiency.

Time complexity: Time complexity of algorithm can be determined by time of the algorithm
but this represents the number of operations are performed while executing the algorithm. An
algorithm time complexity can be determined by its input i.e. the algorithm performs the
operations based on the input size

An algorithm cannot be termed as better because it takes less time units or worse
because it takes more time units in order to execute.

Space complexity: Space complexity of an algorithm can be determined by the number of


variables used in the algorithm. An algorithm complexity in terms of space is determined by
number of variables. The algorithm which uses fewer variables is better in terms of space
complexity. Of these two complexities, the time complexity is important factor in
determining the algorithm efficiency i.e. analyzing the algorithm.

While analyzing the algorithm we could not be interested in the actual number of operations
done for some specific size of input data. Instead, we concentrate on building an equation that
relates the number of operations that a particular algorithm does to the size of the input.

DS NEC, CSE Dept. Page 3


UNIT I Recursion and Linear Search

What to count and consider:-

An algorithm may consist of several operations and it may not be possible to count
every one of them as a function of N, the number of inputs. The difference between an
algorithm that does N+5 operations and one that does N+250 operations becomes
meaningless as N gets large.

So, it is important to decide what to count while analyzing the algorithm. We must identify
the significant operation or operations in the algorithm. Once these are determined we should
determine which of these operations are integral to the algorithm and which are overhead to
the algorithm.

There are two classes of operations that are typically closer for the significant operation-
comparison and arithmetic.

Comparison operators: these operators are used in searching and sorting algorithms. While
searching comparison is done to check if the value is the one we are looking for, whereas in
sorting comparison is done to see whether values being compared are out of order. The
comparison operators include equal, not equal, less than, greater than, less than or equal,
greater than or equal.

Arithmetic operators: The arithmetic operations fall under two groups: Additive and
multiplicative. Additive operators include addition, subtraction, increment, and decrement.
Multiplicative operators include multiplication, division and modulus. These two groups are
counted separately because multiplication is complex and take longer time to execute the
additive operators.

Cases to consider during analysis:-

The algorithm analysis can be determined by the input. So choosing the input to
consider when analyzing an algorithm can have a significant impact on how an algorithm will
perform. E.g.: if the input list is already sorted, some sorting algorithms will perform very
well, but other sorting algorithms may perform poorly. The opposite may be true if the list is
randomly arranged instead of sorted. Hence multiple input sets must be considered while
analyzing an algorithm.

DS NEC, CSE Dept. Page 4


UNIT I Recursion and Linear Search

So, an algorithm can work as best or, average and worst based on the input.

1. Best case:-This represents the input set that allows an algorithm to perform most quickly.
With this input the algorithm takes less time as it causes the algorithm to do the least work.

2. Worst case: This represents the input set that causes the algorithm to perform most slowly.
Worst case is important analysis because it gives us an idea of the most time an algorithm will
ever take. Worst case analysis requires that we identify the input values that cause an
algorithm to do the most work.

3. Average case: This represents the input set that allows an algorithm to deliver an average
performance. Doing average case analysis is a four step process.

(1) Determine the number of difficult groups into which all possible input sets can be
divided.
(2) Determine the probability that the input will come from each of these groups.
(3) Determine how long the algorithm will run for each of these groups. All of the input in
each group should take the same amount of time, and if they do not, the group must be
split into two separate groups.
(4) Calculate the average case time using the formula A (n) = pi * ti where i is from 1 to m.

Here n= size of input, m= Number of groups, pi = probability that the input will be from
group i, ti = time that the algorithm takes for input from group i.

Linear search:

This is the simplest method of searching. In this method, the element to be found is
sequentially searched in the list. This method can be applied to a sorted or an unordered list.
Searching is the case of a list starts from 0 element and continues until the element is found
or the end of list is reached.

Example:

Index: 0 1 2 3 4 5 6 7 8 9
A[]= 11 2 9 13 57 25 17 1 90 3

Target 57

DS NEC, CSE Dept. Page 5


UNIT I Recursion and Linear Search

The linear search starts its search from first element i.e. from location 0 to end of the list i.e.
n-1 location, where n is no of elements. The search moves sequentially from 0 locations, 1
location ... to n-1 location.

1 comparison: 11 2 9 13 57 25 17 1 90 3
Target: 57 Not Match
2 comparison: 11 2 9 13 57 25 17 1 90 3
Target: 57 Not Match
3 comparison: 11 2 9 13 57 25 17 1 90 3
Target: 57 Not Match
4 comparison: 11 2 9 13 57 25 17 1 90 3
Target: 57 Not Match
5 comparison: 11 2 9 13 57 25 17 1 90 3
Target: 57 Match

Linear search algorithm: (Non-Recursion)

lsnr (a,num,target)
a: Array elements in a
num: Num of elements in a
target: Target element to be searched
begin
initialize flag=0
for i=0 to num-1
if target=a[i]
write element found
flag=1
break
end of if
end of for
if flag=0
write element is not found
end of if
end of lsnr

DS NEC, CSE Dept. Page 6


UNIT I Recursion and Linear Search

Linear search algorithm (recursion)

Lsr (a,num,target,index)
a: Array elements in a
num: No of elements in a
target: The element to be searched
index: current position in array
begin
initialize flag=0
if a[index]=target
write element found
flag=1
break
otherwise
if(flag=0&&index<num)
write element not found
break
otherwise
call lsr(a,num,target,index+1)
end of if
end of if
end of lsr.

Program for Linear Search:

#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int a[100],i,num,target,index,flag=0,ch;
clrscr();
while(1)
{
printf("Linear search\n");
printf("1. For recursion\n 2. For Non-Recursion\n");
printf("3.Exit\n");
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("enter the no of elements\n");
scanf("%d",&num);
printf("enter the array elements\n");
for(i=0;i<num;i++)
scanf("%d",&a[i]);
printf("enter the target\n");
scanf("%d",&target);

DS NEC, CSE Dept. Page 7


UNIT I Recursion and Linear Search

index=0;
flag=lsr(a,num,target,index);
if(flag==0)
printf("element not found\n");
else
printf("element found");
getch();
break;
case 2: printf("enter the no of elements\n");
scan("%d",&num);
printf("enter the array elements\n");
for(i=0;i<num;i++)
scanf("%d",&a[i]);
printf("enter the target\n");
scanf("%d",&target);
flag=lsnr(a,num,target);
if(flag==0)
printf("elements not found\n");
else
printf("element not found\n);
getch();
break;
default: exit(0);
}
}
}

int lsr(int a[],int num,int target,int index)


{
int flag=0;
if(a[index]==target)
{
flag=1;
return flag;
}
else
if(((num-1)==index&&(flag==0)))
return 0;
else
return lsr(a,num,target,index+1);
}
}

int lsnr(int a[],int num,int target)


{
int flag=0,i=0;
for(i=0;i<num;i++)
{
if(a[i]==target)

DS NEC, CSE Dept. Page 8


UNIT I Recursion and Linear Search

return flag=1;
}
return flag=0;
}

Binary search:

Binary search method is very fast and efficient. This method requires that the list of elements
be in sorted order. In this method, to search an element we compare it with the element
present at the center of the list. If it matches then the search is successful. Otherwise the list is
divided into two halves. One from 0 element to center element(first half) and the another
from center element to last element(second half).As a result, all the elements in the first half
are smaller than the center element ,whereas the elements in the second half are greater than
the center element. The searching will now proceed in either of the two halves depending
upon whether the element is greater or smaller than the center element. If the element is
smaller than the center element then the searching will be done in first half, otherwise in the
second half. Same process of comparing the required element with the center element and if
not found then dividing elements into two halves is repeated for the first half or second half.
This procedure is repeated till the element is found or the division of half parts gives one
element.

Example:
Index: 0 1 2 3 4 5 6 7 8 9
Array [ ]: 1 2 3 9 11 13 17 25 57 90
Target: 57
Suppose an array consists of ten sorted numbers and 57 is element that is to be searched. The
binary search method when applied to this array works as follows.
(a) 57 are compared with the element present at the center of the list (i.e. 11). Since 57 are
greater than 11, the searching is restricted only to the second half of the array.
(b) Now 57 is compared with the center element of the second half of the array (i.e. 25). Here
again 57 is greater than 25.So the searching now process in the elements present between
the 25 and the last element 90.
(c) This process is repeated till 57 is found or no further division of sub-array is possible

(a) 1 2 3 9 11 13 17 25 57 90 Target: 57

DS NEC, CSE Dept. Page 9


UNIT I Recursion and Linear Search

(b) 1 2 3 9 11 13 17 25 57 90 Target: 57
(c) 1 2 3 9 11 13 17 25 57 90 Target: 57

Binary Search Algorithm (Non-recursion)


bsnr(a,num,target)
a:Array elements in a
num:No of elements in array a
target:The element to be searched.
begin
initialize start=0,end=num-1,flag=0,middle;
while start<=end do
middle=(start+end)/2;
if a[middle]=target then
write element found
flag=1
break
otherwise
if(a[middle]<target then
start=middle+1
otherwise
end=middle-1
end of if
end of if
end of while
if flag=0 then
write element not found
end of bsnr

Binary Search Algorithm (Recursion):


bsr(a,start,end, target)
a:Array elements in a
start:starting point in a
end:ending point in a
target:The target element
begin
initialize middle,flag=0;
if start<=end then
middle=(start+end)/2
if a[middle]=target then
write element found
flag=1
break
otherwise
if a[middle]<target then
call bsr(a,middle+1,end,target)
otherwise
call bsr(a,start,middle-1,target)
DS NEC, CSE Dept. Page 10
UNIT I Recursion and Linear Search

end of if
end of if
end of if
if flag=0 then
write element found
end of bsr

Program:
void main()
{
int a[20],num,target,i,start,end,flag=0,ch;
clrscr();
while(1)
{
printf("binary search\n");
printf("1. Recursion\n");
printf("2. Non-recursion\n");
printf("3.exit\n");
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("enter the no of elements\n");
scanf("%d",&num);
printf("enter array elements\n");
for(i=0;i<num;i++)
scanf("%d",&a[i]);
printf("enter the target element\n");
scanf("%d",&target);
flag=bsr(a,0,num-1,target);
if(flag=0)
printf("element not found\n");
else
printf("element is found\n");
getch();
break;
case 2: printf("enter the no elements\n");
scanf("%d",&num);
printf("enter the array elements\n");
for(i=0;i<num;i++)
scanf("%d",&a[i]);
printf("enter the target element");
scanf("%d",&target);
flag=bsnr(a,num,target);
if(flag==0)
printf("element not found\n");
else
printf("element found\n");
getch();

DS NEC, CSE Dept. Page 11


UNIT I Recursion and Linear Search

break;
default: exit(0);
}
}
}
int bsr(int a[],int start,int end,int target)
{
int middle,flag=0;
if(start<=end)
{
middle=(start+end)/2;
if(a[middle]==target)
{
flag=1;
return flag;
}
else
{
if(a[middle]<target)
return bsr(a,middle+1,end,target);
else
return bsr(a,start,middle-1,target);
}
}
return flag;
}
int bsnr(int [a],int num,int target)
{
int start=0,end=num-1,middle,flag=0;
while(start<=end)
{
middle=(start+end)/2;
if(a[middle]=target)
{
return flag=1;
}
else
{
if(a[middle]<target)
start=middle+1;
else
end=middle-1;
}
}
return flag;
}
Fibonacci Search:

DS NEC, CSE Dept. Page 12


UNIT I Recursion and Linear Search

Fibonacci search is a search in which the elements in a list can be searched using Fibonacci
sequence: 0,1,1,2,3,5,8,15.............. Using Fibonacci sequence, the elements in a list are
searched. The Fibonacci sequence is used to find the index position of array list. There the
array list elements are in sorted order.

Algorithm:

Fsnr (list,num,target)
list: list of array elements
num: num of elements in list
target: target element in the list
begin
initialize fib1=0,fib2=1,fib=fib1+fib2,flag=0,i,index;
while fib<=num do
fib2=fib1;
fib1=fib;
fib=fib1+fib2;
end of while
while fib>1 do
i=((index+fib2)<num)?(index+fib2):num;
if target=list[i] then
return flag=1;element found
otherwise
if list[i] < target then
fib=fib1;
fib1=fib2;
fib2=fib-fib1; index=i;
otherwise
if target<list[i] then
fib=fib2;
fib1=fib1-fib2;
fib2=fib-fib1;
end of if;
end of while;
return flag, element not found
end of fsnr

Program:
#include<stdio.h>
#include<conio.h>
#include<process.h>

void main()
{
int a[20],i,num,target,fib1=0,fib2=1,fib=fib1+fib2,index=0,flag=0,ch;
clrscr();

DS NEC, CSE Dept. Page 13


UNIT I Recursion and Linear Search

while(1)
{
fib1=0,fib2=1,fib=fib1+fib2;
printf("fibonacci search\n");
printf("1. recursion\n");
printf("2. non-recursion\n");
printf("3.exit\n");
printf("enter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("enter the no of elements\n");
scanf("%d",&num);
printf("enter the array elements\n");
for(i=1;i<=num;i++)
scanf("%d",&a[i]);
printf("enter the target\n");
scanf("%d",&target);
index=0,i=0;
while(fib<=num)
{
fib2=fib1;
fib1=fib;
fib=fib1+fib2;
}
flag=fsr(a,num,target,fib,fib1,fib2,i,index);
if(flag==0)
printf("element not found\n");
else
printf("element found\n");
getch();
break;

case 2: printf("enter the no of elements\n");


scanf("%d",&num);
printf("enter array elements\n");
for(i=1;i<=num;i++)
scanf("%d",&a[i]);
index=0,i=0;
flag=fsnr(a,num,target);
if(flag==0)
printf("element not found\n");
else
printf("element found\n");
getch();
break;
default: exit(0);
}/*switch*/
}/*while*/

DS NEC, CSE Dept. Page 14


UNIT I Recursion and Linear Search

}/*main*/

int fsr(int a[],int num,int target,int fib,int fib1,int fib2,int i,int index)
{
int flag=0;
if(fib>1)
{
i=(((index+fib2))<num)?(index+fib2):num;
if(target==a[i])
return flag=1;
else
if(target<a[i])
{
fib=fib2;
fib1=fib1-fib2;
fib2=fib-fib1;
return fsr(a,num,target,fib,fib1,fib2,i,index);
}
else
if(target>a[i])
{
fib=fib1;
fib1=fib2;
fib2=fib-fib1;
index=i;
return fsr(a,num,target,fib,fib1,fib2,i,index);
}
}
return flag;
}
int fsnr(int a[],int num,int target)
{
int fib1=0,fib2=1,fib=fib1+fib2,i=0,index=0,flag=0;
while(fib<=num)
{
fib2=fib1;
fib1=fib;
fib=fib1+fib2;
}
while(fib>1)
{
i=((index+fib2)<num)?(index+fib2):num;
if(target==a[i])
return flag=1;
else
{
fib=fib2;
fib1=fib1-fib2;
fib2=fib-fib1;

DS NEC, CSE Dept. Page 15


UNIT I Recursion and Linear Search

}
else
if(target>a[i])
{
fib=fib1;
fib1=fib2;
fib2=fib-fib1;
index=i;
}
}
return flag;
}

Recursion:

Recursion is a repetitive process in which an algorithm calls itself i.e. when a function of
body calls the same function then it is called as recursion.

Recursive procedure:

If p is a procedure containing a call statement to itself or to another procedure that


result in a call to itself, then the procedure p is called as recursive procedure. The former case
is called as direct recursion and the latter is termed as indirect recursion.

Procedure P Procedure p
Call P Call Q

Call P

(a) Direct Recursion (b) Indirect Recursion

e.g.: void recursion ()


{
printf ("recursion\n");
recursion ();
}/*No termination condition*/

In the above function, the control will not come out of the function till memory is not
available since there is no termination condition.

The recursive procedure must have the following two properties:

DS NEC, CSE Dept. Page 16


UNIT I Recursion and Linear Search

(1) These must be a certain criteria i.e. there must be at least one terminate condition to end
the recursion.
(2) A recursion function does contain the function that calls itself and may not have looping
statements.

Advantages:

(1) Easy to use


(2) Reduces the complexity in coding.

Disadvantage: It is slower compared to the normal looping statement.

Types:

A recursion can be classified based on the number of calls to itself with in the body of
function.
(1) Linear recursion: A recursive function which calls itself for one time during the course
of its execution. A linear recursion is a function that only makes a single call to itself each
time the function runs.
E.g. Factorial of a number is an example of recursion.

(2) Binary recursion: A recursive function which calls itself twice during the course of its
execution. Some recursive functions do not just have one call to themself, some might have
two or more calls to itself. This is referred as binary recursion.
E.g. Fibonacci sequence of a number is an example of recursion.

(3) Tail recursion: Tail recursion is a form of linear recursion. In tail recursion, the recursive
call is the last thing the function does, often the value of the recursive call is returned. A
function call is said to be a tail recursive if there is nothing to do after the function returns
except return its value or immediately returns the calling function.
E.g. Gcd of two numbers is an example of tail recursion

Recursive algorithms:

For Factorial function:

The product of the positive integers from 1 to n, inclusive, is called "n factorial" and is
usually denoted by n!

DS NEC, CSE Dept. Page 17


UNIT I Recursion and Linear Search

n!=1.2.3.....(n-2).(n-1).(n). Where n is positive integer

In factorial calculation, the factorial of zero (0) is 0! = 1, 1! = 1, 2! = 1.2, and so on.

The factorial function may be defined as follows

if n=0 or n=1 then n! =1.


Otherwise i.e. n>1 then n! = n.(n-1)!.

Observe that this definition of n! is recursive, since it refers to itself when it uses (n-1)!

e.g.: 4!
(1) 4! =4.3!
(2) 3! =3.2!
(3) 2! =2.1!
(4) 1! =1.0! =1.1=1
(5) 2! =2.1=2
(6) 3! =3.2=6
(7) 4! =4.6=24

Therefore, the algorithm of factorial can be returned as follows

1. If n=0 or 1
then set fact=1 and return
2. if n>1 then
repeat from n to 1
return n.(n-1)!
3. display result
num: number is to compute factorial
if num==1 then
return 1
otherwise
return num.fact(num-1)
end of fact.

Program:

int fact(int num)


{
if(num==1||num==0)
return 1;
else
return num*fact(num-1);

DS NEC, CSE Dept. Page 18


UNIT I Recursion and Linear Search

For Fibonacci sequence:

The Fibonacci sequence usually denoted by f0, f1, f2........and follows

The Fibonacci sequence is started by initializing f0 and f1 to 0 and 1 respectively. The next
sequence is calculated by adding the previous two fibonacci values.

Therefore f2=f1+f0=1+0=1
f3=f2+f1=1+1=2
f4=f3+f2=2+1=3 and so on.

Fibonacci sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21

Definition:

a. if n=0 or n=1 then return 0 or 1.


b. if n>1 then fn =fn-2+fn-1.

The algorithm of fibonacci can be called recursively, since the value of Fibonacci number is
dependent on previous values. Therefore, the algorithm of Fibonacci sequence can be written
as follows

Algorithm:

fibonacci (num)
num : number to compute fibonacci sequence
if num==0 or num=1 then
return num
otherwise
call fibonacci(num-2)+fibonacci(num-1)
end of fibonacci function
program:

int fib(int num)


{
if((num==0)||(num==1))
return num;
else
return fib(num-2)+fib(num-1);
}
DS NEC, CSE Dept. Page 19
UNIT I Recursion and Linear Search

e.g.: fib (5) =?


fib (5) = fib (4) + fib (3)
fib (5)

fib (4) fib (3)

fib (3) fib (2) fib (2) fib (1)

fib (2) fib (1) fib (1) fib (0) fib (1) fib (0) return 1

fib (1) fib (0) return 1 return 1 return 0 return 1 return 0

return 1 return 0

GCD:

GCD is the greatest common divisor of two numbers.

e.g.: 10, 5
10=5*2
5=5*1
The common divisor is 5; therefore gcd of 10 and 5 is 5.

Gcd of two numbers can be calculated by following method

e.g.: 424,632
424)632(1
424
-------
208)424(2
416
--------
8)208(26
208
--------
0 Therefore gcd of 424 and 632 is 8

Definition:

Let a,b are two numbers


if(a>b) then
call gcd(a,b)
otherwise
call gcd(b,a)
gcd(a,b) definition:
if a%b=0 then
gcd is b

DS NEC, CSE Dept. Page 20


UNIT I Recursion and Linear Search

otherwise
call gcd(b,a%b)

Algorithm:

gcd(a,b)
a:number to compute gcd of a&b
b:number to compute gcd of a&b
if(a<b) then
exchange a&b
if(a%b=0) then
return b
otherwise
return gcd(b,a%b)
end of gcd function

Program:

int gcd(int a,int b)


{
int temp;
if(b>a)
{
temp=b;
b=a;
a=temp;
}
if((a%b)==0)
return b;
else
return gcd(b,a%b);
}

Towers of Hanoi:

Problem: Three pegs A, B and C are there in which peg A has certain number of disks (N)
which are of differing diameters which are arranged in a way that a larger disk is always
below a smaller disk.

Objective: To move the N disks from peg A to peg C using peg B as auxiliary peg

DS NEC, CSE Dept. Page 21


UNIT I Recursion and Linear Search

Rules:
1) Only one disk has to be moved from one peg to other peg.
2) Larger disk may never rest on a smaller disk.

Solution: Consider that there are n disks,

The following is the recursive solution,

(1) Suppose, if we had solution for n-1 disks i.e. disks are moved from peg A to peg B using
peg C as auxiliary.
(2) Now move the larger disk (nth disk) to peg C
(3) Now move the n-1 disks from peg B to peg C using peg A as auxiliary.

The no of steps in moving disks from peg A to peg C using peg B as auxiliary can be
computed by formula
no of steps=2(no of disks)-1 e.g. If no of disks =3 then no of steps=2^(3)-1=7

The following figure explains how the pegs are moved from one tower to other tower in order
to move the pegs from tower A to tower C.

DS NEC, CSE Dept. Page 22


UNIT I Recursion and Linear Search

Algorithm:

towers of Hanoi (num, A, B, C)


num: no of disks on peg A
A: peg A, source peg
B: peg B, auxiliary peg
C: peg C, destination peg
if (num==1)
move disk 1 from A to C
otherwise
move num-1 disks from A to B
move disk num from A to C
move num-1 disks from B to C
end of if
end of towers of Hanoi

Program:

void TOI(int num, char A, char B, char C);


{
if(num==1)
DS NEC, CSE Dept. Page 23
UNIT I Recursion and Linear Search

printf("move %d from %c to %c\n",num, A ,C);


else
{
TOI(num-1,A,C,B);
printf("move %d from %c to %c\n",num, A, C);
TOI(num-1,B,A,C);
}
}

Tail recursion:
A function call is said to be tail recursive if there is nothing to be done after the function
return its value or immediately returns the call function.

e.g.: int factorial (int n, int accumulator)


{
if (n==0||n==1)
return accumulator;
return factorial (n-1, n*accumulator);
}
void main()
{
int num,res;
clrscr();
printf(Enter the Number\n);
scanf(%d,&num);
res=factorial (num, 1)
printf(The Factorial of %d is %d\n,num,res);
getch();
}
Tail recursion is interesting because it is form of recursion that can be implemented much
more efficiently than general recursion. In general, a recursive call requires the compiler to
allocate the storage on stack at runtime for every call that has not yet returned. The memory
consumption makes recursion unacceptably inefficient for representing repetitive algorithms
having large and unbounded size.

Tail recursion is the special case of recursion i.e. semantically equivalent to the iteration
constructs normally used to represent repetition programs.

DS NEC, CSE Dept. Page 24

You might also like