0% found this document useful (0 votes)
4 views50 pages

recursionnew

The document discusses recursive algorithms, explaining the concept of recursion and providing examples such as calculating factorials, listing directory contents, generating anagrams, and solving the Towers of Hanoi puzzle. It highlights the advantages and disadvantages of recursion compared to iteration, including overhead costs and potential inefficiencies in certain cases like the Fibonacci sequence. Additionally, it covers tree data structures, their traversal methods, and searching techniques within collections.

Uploaded by

subrata
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)
4 views50 pages

recursionnew

The document discusses recursive algorithms, explaining the concept of recursion and providing examples such as calculating factorials, listing directory contents, generating anagrams, and solving the Towers of Hanoi puzzle. It highlights the advantages and disadvantages of recursion compared to iteration, including overhead costs and potential inefficiencies in certain cases like the Fibonacci sequence. Additionally, it covers tree data structures, their traversal methods, and searching techniques within collections.

Uploaded by

subrata
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/ 50

Recursive Algorithms

CS 180
Sunil Prabhakar
Department of Computer Science
Purdue University

Tuesday, April 10, 2012


Recursive Algorithms
n Within a given method, we are allowed to
call other accessible methods.
n It is also possible to call the same method
from within the method itself.
n This is called a recursive call.
n For certain problems a recursive solution is
very natural and simple.
n It is possible to implement a recursive
algorithm without using recursion, but the
code can be more complex.
2

Tuesday, April 10, 2012


Example of Recursion
n The factorial of N is the product of the first N
positive integers:
N! = N * (N – 1) * (N – 2 ) * . . . * 2 *1
n This is useful for many situations, e.g.
¡ there are n! possible sequences of n objects
¡ there are n!(n-k)!/k! unique subsets of size k, from a
set of size n.
n The factorial of N can be defined recursively as

{
factorial(n) =
n * factorial(n-1) if n>1

1 otherwise

Tuesday, April 10, 2012


Recursive Method
n An recursive method is a method that contains a
statement (or statements) that makes a call to itself.
n Implementing the factorial of N recursively will result in the
following method.

public int factorial( int N ) {


Test to stop or
continue. if ( N == 1 ) {
End case: recursion return 1;
stops.
}
else {
Recursive case:
recursion continues. return N * factorial( N-1 );
}
}

Tuesday, April 10, 2012


The details …
n As with any call, a recursive call results in the
creation of temporary workspace for the called
method and copying of parameters.
n Each call to a method results in the creation of a
separate workspace with new copies of variables
(local and formal parameters).
n When a recursive call ends, flow returns to the
caller.

Tuesday, April 10, 2012


Example factorial( 3 );

public int factorial( int N ) {


if ( N == 1 ) {
return 1;
} else {
N 3
return N * factorial( N-1 );
}
}

public int factorial( int N ) {


if ( N == 1 ) {
return 1;
} else { N 2
return N * factorial( N-1 );
}
}

public int factorial( int N ) {


if ( N == 1 ) {
return 1;
} else { N 1
return N * factorial( N-1 );
}
}

Tuesday, April 10, 2012


6
Example factorial( 3 );

public int factorial( int N ) {


if ( N == 1 ) {
return 1;
} else { 2 N 3
return N * factorial( N-1 );
}
}

public int factorial( int N ) {


if ( N == 1 ) {
return 1;
} else { 1 N 2
return N * factorial( N-1 );
}
}

public int factorial( int N ) {


if ( N == 1 ) {
return 1;
} else { N 1
return N * factorial( N-1 );
}
}

Tuesday, April 10, 2012


Directory Listing
n List the names of all files in a given directory and
its subdirectories.
public void directoryListing(File dir) {
//assumption: dir represents a directory
String[] fileList = dir.list(); //get the contents
String dirPath = dir.getAbsolutePath();

for (int i = 0; i < fileList.length; i++) {


Test File file = new File(dirPath + "/" + fileList[i]);

if (file.isFile()) { //it's a file


End case System.out.println( file.getPath() );
} else {
Recursive case directoryListing( file ); //it's a directory
} //so make a
} //recursive call
}
8

Tuesday, April 10, 2012


Anagram
n List all anagrams of a given word.

Word CAT

CTA
ATC
ACT Anagrams

TCA
TAC

Tuesday, April 10, 2012


Anagram Solution
n The basic idea is to make recursive calls on a
sub-word after every rotation. Here’s how:
CAT
C A T Recursion
CTA
Rotate Left

ATC
A T C Recursion
ACT
Rotate Left

TCA
T C A Recursion
TAC
10

Tuesday, April 10, 2012


Anagram Method
public void anagram( String prefix, String suffix ) {
String newPrefix, newSuffix;
Test int numOfChars = suffix.length();

if (numOfChars == 1) {
//End case: print out one anagram
End case System.out.println( prefix + suffix );

} else {
for (int i = 1; i <= numOfChars; i++ ) {
newSuffix = suffix.substring(1, numOfChars);
newPrefix = prefix + suffix.charAt(0);
anagram( newPrefix, newSuffix );
Recursive case //recursive call
//rotate left to create a rearranged suffix
suffix = newSuffix + suffix.charAt(0);
}
}
}

11

Tuesday, April 10, 2012


Towers of Hanoi
n The goal of the Towers of Hanoi puzzle is to move
N disks from Peg 1 to Peg 3:
– Only one disk
Start: can be moved at
a time.
– A larger disk
Peg1 Peg2 Peg3
cannot be placed
on top of a
smaller disk.
Goal:

Peg1 Peg2 Peg3

12

Tuesday, April 10, 2012


Towers of Hanoi Solution

Peg1 Peg2 Peg3

Peg1 Peg2 Peg3


Peg1 Peg2 Peg3

Peg1 Peg2 Peg3


13

Tuesday, April 10, 2012


towersOfHanoi Method
public void towersOfHanoi(int N, //number of disks
int from, //origin peg
int to, //destination peg
Test int spare ){//"middle" peg

if ( N == 1 ) {

End case moveOne( from, to );

} else {
towersOfHanoi( N-1, from, spare, to );
Recursive case moveOne( from, to );
towersOfHanoi( N-1, spare, to, from );
}
}

private void moveOne( int from, int to ) {


System.out.println( from + " ---> " + to );
}

14

Tuesday, April 10, 2012


Recursion vs Iteration
n Recursion has greater overhead due to
method calls, variable setups etc.
n Recursion provides cleaner solutions
n Can be simulated using iteration and a
stack-like structure
¡ may add too much complexity (consider an
iterative solution for Towers of Hanoi)

15

Tuesday, April 10, 2012


When Not to Use Recursion
n When recursive algorithms are designed carelessly,
it can lead to very inefficient and unacceptable
solutions.
n For example, consider the following:

public int fibonacci( int N ) {

if (N == 0 || N == 1) {
return 1;

} else {
return fibonacci(N-1) + fibonacci(N-2);
}
}

16

Tuesday, April 10, 2012


Excessive Repetition
n Recursive Fibonacci ends up repeating the
same computation numerous times.
fibonacci(5)

fibonacci(4)+fibonacci(3)

fibonacci(2)+fibonacci(1)

fibonacci(1)+fibonacci(0)

fibonacci(3)+fibonacci(2)

fibonacci(1)+fibonacci(0)

fibonacci(2)+fibonacci(1)

fibonacci(1)+fibonacci(0)
17

Tuesday, April 10, 2012


Non-recursive Fibonacci
public int fibonacci( int N ) {

int fibN, fibN1, fibN2, cnt;

if (N == 0 || N == 1 ) {
return 1;

} else {

fibN1 = fibN2 = 1;
cnt = 2;
while ( cnt <= N ) {
fibN = fibN1 + fibN2; //get the next fib no.
fibN1 = fibN2;
fibN2 = fibN;
cnt ++;
}
return fibN;
}
}

18

Tuesday, April 10, 2012


Quiz
n What does the following method compute
for N>0?
public int recurse( int N ) {

A. N2
if (N == 1 ) {
return 2; B. 2N
C. N!
} else {
D. (N-1)!
return 2*recurse(N-1);
}
}

19

Tuesday, April 10, 2012


Overhead of recursion
n Remember that each recursive call is
expensive
¡ create local variables for each call
¡ copy arguments into local variables
¡ track the execution point for each call
¡ returned values are copied back
¡ local space is reclaimed

20

Tuesday, April 10, 2012


When Not to Use Recursion

n In general, use recursion if


¡ A recursive solution is natural and easy to
understand.
¡ A recursive solution does not result in excessive
duplicate computation.
¡ The equivalent iterative solution is too complex.

21

Tuesday, April 10, 2012


Trees
n Trees are a very commonly used data
structure in Computer Science
n For example, simple binary trees can be
used to maintain a sorted list of strings
n Suppose we had an unknown number of
strings to input, sort, then output
n We could use linked lists
¡ Have to modify insert to ensure sorted order
n Or, we can use trees
¡ more efficient
22

Tuesday, April 10, 2012


A Sorted Binary Tree
d, b, a, e, f, c, do, dot

b e

a c do f

dot

23

Tuesday, April 10, 2012


The Sorted Binary Tree Node
class SBTNode {
private SBTNode left, right; :SBTNode
private String content;
content
public SBTNode (String c) {
left = right = null; left
content = c;
} right
public void insert(String c){
if(c.compareTo(this.content)<=0)
if(left==null)
left = new SBTNode(c);
else

else
left.insert(c); content
if(right==null)
right = new SBTNode(c);
left right
else
right.insert(c );
}
. . .

24

Tuesday, April 10, 2012


Binary Tree Node Class (cont.)

. . .
public void print(){
if(left!=null)
left.print();
System.out.println(content);
if(right!=null)
right.print();
}
}

25

Tuesday, April 10, 2012


Example Use

public static void main (String[] args) {

SBTNode root = null;


String input;

input = JOptionPane.showInputDialog(null, “Enter String”);


if(input.length()>0) {
root = new SBTNode(input);
while(true){
input= JOptionPane.showInputDialog(null, “Enter String”);
if(input.length()<1)
break;
root.insert(input);
}
root.print();
}
}

26

Tuesday, April 10, 2012


Expression Trees
5*x+ 2*y
+ +

* *
+ /
5 x 2 y
* * z v

5 x 2 y

5*x+ 2*y + z/v

27

Tuesday, April 10, 2012


Tree traversal
n Visiting all the nodes of a tree is called a
tree traversal
¡ e.g.,in earlier example, we visited and printed
out each node
n Important types of traversals
¡ In order: left child, parent, right child
n e.g., sorted output
¡ Post order: left child, right child, parent
n e.g., to get postfix version of expression
n useful for expression evaluation using a stack

¡ Pre order: parent, left child, right child


n e.g., to get prefix version of expression
28

Tuesday, April 10, 2012


Expression Tree Traversals

+ +

* *
+ /
5 x 2 y
* * z v
In: 5*x+ 2*y
Post: 5x*2y*+ 5 x 2 y
Pre: +*5x*2y
In: 5*x+ 2*y + z/v
Post: 5x*2y*+zv/+
Pre: ++*5x*2y/zv
29

Tuesday, April 10, 2012


General Trees
n In general, trees may have
¡ more than two children
¡ no ordering among children
n They don’t have:
¡ cycles, multiple parents, single root
n More general structure: graph
n Applications:
¡ class hierarchy,
¡ index structures (databases)
30

Tuesday, April 10, 2012


Tree Traversal

. . .
public void inOrderPrint(){
if(left!=null)
left.print();
System.out.println(content);
if(right!=null)
right.print();
}

public void preOrderPrint(){


System.out.println(content);
if(left!=null)
left.print();
if(right!=null)
right.print();
}
}

31

Tuesday, April 10, 2012


Searching
n When we maintain a collection of data, one of the
operations we need is a search routine to locate desired
data quickly.
n Array searching
¡ Given an array of values and a search key, return

n the index of the key if found

n -1 if key is not in the array

n Linear search
n Binary search
¡ logarithmic performance, but requires sorted data

32

Tuesday, April 10, 2012


Search Result
Unsuccessful Search: search( 45 ) NOT_FOUND

Successful Search: search( 12 ) 4

number
0 1 2 3 4 5 6 7 8
23 17 5 90 12 44 38 84 77

33

Tuesday, April 10, 2012


Linear Search

n Search the array from the first to the last


position in linear progression.

public int linearSearch ( int[] number, int searchValue ) {


int loc = 0;
while (loc < number.length && number[loc] != searchValue) {
loc++;
}
if (loc == number.length) { //Not found
return NOT_FOUND;
} else {
return loc; //Found, return the position
}
}

34

Tuesday, April 10, 2012


Binary Search Routine

public int binarySearch (int[] number, int searchValue) {

int low = 0,
high = number.length - 1,
mid = (low + high) / 2;
while (low <= high && number[mid] != searchValue) {
if (number[mid] < searchValue) {
low = mid + 1;
} else { //number[mid] > searchValue
high = mid - 1;
}
mid = (low + high) / 2; //integer division will truncate
}
if (low > high) {
mid = NOT_FOUND;
}
return mid;
}

35

Tuesday, April 10, 2012


Binary Search Performance
n Successful Search
¡ Best Case – 1 comparison
¡ Worst Case – log2N comparisons
n Unsuccessful Search
¡ Best Case = Worst Case – log2N comparisons
n Since the portion of an array to search is cut into
half after every comparison, we compute how
many times the array can be divided into halves.
n After K comparisons, there will be N/2K elements
in the list. We solve for K when N/2K = 1,
deriving K = log2N.

36

Tuesday, April 10, 2012


Comparing N and log2N Performance
Array Size Linear – N Binary – log2N

37

Tuesday, April 10, 2012


Sorting
n When we maintain a collection of data, many applications
call for rearranging the data in certain order, e.g. arranging
Person information in ascending order of age.
n Here’s the problem statement:

Given an array of N integer values, arrange the values into


ascending order.

n We will count the number of comparisons the algorithms


make to analyze their performance.
¡ The ideal sorting algorithm will make the least possible number of
comparisons to arrange data in a designated order.
n We will compare different sorting algorithms by analyzing
their worst-case performance.
38

Tuesday, April 10, 2012


Selection Sort
first min
1. Find the smallest
element in the list. 0 1 2 3 4 5 6 7 8
23 17 5 90 12 44 38 84 77
2. Exchange the element in
the first position and the
smallest element. Now the exchange
smallest element is in the
first position.
0 1 2 3 4 5 6 7 8
3. Repeat Step 1 and 2 with
the list having one less 5 17 23 90 12 44 38 84 77
element (i.e., the smallest
element is discarded from
further processing). sorted unsorted

This is the result of one pass.

39

Tuesday, April 10, 2012


Selection Sort Passes
Pass # 0 1 2 3 4 5 6 7 8

1 5 17 23 90 12 44 38 84 77
Result AFTER one
pass is completed.
sorted

2 5 12 23 90 17 44 38 84 77

3 5 12 17 90 23 44 38 84 77

7 5 12 17 23 38 44 77 84 90

8 5 12 17 23 38 44 77 84 90

40

Tuesday, April 10, 2012


Selection Sort Routine
public void selectionSort( int[] number )
{
int startIndex, minIndex, length, temp;
length = number.length;

for (startIndex = 0; startIndex <= length-2; startIndex++){


//each iteration of the for loop is one pass
minIndex = startIndex;

//find the smallest in this pass at position minIndex


for (i = startIndex+1; i <= length-1; i++) {
if (number[i] < number[minIndex]) minIndex = i;
}
//exchange number[startIndex] and number[minIndex]
temp = number[startIndex];
number[startIndex] = number[minIndex];
number[minIndex] = temp;
}
}

41

Tuesday, April 10, 2012


Selection Sort Performance

n We derive the total number


of comparisons by counting
the number of times the
inner loop is executed.
n For each execution of the
outer loop, the inner loop is
executed length – start
times.
§ The variable length is the size of
the array. Replacing length with
N, the array size, the sum is
derived as…
42

Tuesday, April 10, 2012


Bubble Sort
n With selection sort, we make one exchange at the
end of one pass.
n Bubble sort improves the performance by making
more than one exchange during each pass.
n By making multiple exchanges, we will be able to
move more elements toward their correct
positions using the same number of comparisons
as the selection sort makes.
n The key idea of the bubble sort is to make
pairwise comparisons and exchange the positions
of the pair if they are out of order.

43

Tuesday, April 10, 2012


One Pass of Bubble Sort
0 1 2 3 4 5 6 7 8
23 17 5 90 12 44 38 84 77 17 5 23 12 44 90 38 84 77

exchange exchange

17 23 5 90 12 44 38 84 77 17 5 23 12 44 38 90 84 77

exchange exchange

17 5 23 90 12 44 38 84 77
17 5 23 12 44 38 84 90 77
exchange
ok exchange

17 5 23 12 90 44 38 84 77 17 5 23 12 44 38 84 77 90

exchange The largest value 90 is at the end of


the list.
44

Tuesday, April 10, 2012


Bubble Sort Routine

public void bubbleSort(int[] number) {

int temp, bottom, i;


boolean exchanged = true;
bottom = number.length - 2;

while (exchanged) {

exchanged = false;
for (i = 0; i <= bottom; i++) {

if (number[i] > number[i+1]) {


temp = number[i]; //exchange
number[i] = number[i+1];
number[i+1] = temp;
exchanged = true; //exchange is made

}
}
bottom--;
}
}
45

Tuesday, April 10, 2012


Bubble Sort Performance
n In the worst case, the outer while loop
is executed N-1 times for carrying out
N-1 passes.
n For each execution of the outer loop,
the inner loop is executed bottom+1
times. The number of comparisons in
each successive pass is N-1, N-2, … ,
1. Summing these will result in the
total number of comparisons.
• So the performances of the bubble
sort and the selection sort are
approximately equivalent. However, on
the average, the bubble sort performs
much better than the selection sort
because it can finish the sorting
without doing all N-1 passes.

46

Tuesday, April 10, 2012


Quicksort
n To sort an array from index low to high, we
first select a pivot element p.
¡ Any element may be used for the pivot, but for
this example we will user number[low].
n Move all elements less than the pivot to the
first half of an array and all elements larger
than the pivot to the second half. Put the
pivot in the middle.
n Recursively apply quicksort on the two
halves.

47

Tuesday, April 10, 2012


Quicksort Partition

low high

p ...

Any element can be used partition


as a pivot. For simplicity, we
use number[low] as pivot. number[i]<p number[i]>p

Quicksort mid Quicksort

48

Tuesday, April 10, 2012


Method quicksort

public void quickSort( int[] number,


int low, int high ) {

if ( low < high ) {

int mid = partition( number, low, high );

quickSort( number, low, mid-1 );


quickSort( number, mid+1, high );
}
}

49

Tuesday, April 10, 2012


Quicksort Performance
n In the worst case, quicksort executes roughly the same
number of comparisons as the selection sort and bubble
sort.
n On average, we can expect a partition process to split the
array into two roughly equal subarrays.

50

Tuesday, April 10, 2012

You might also like