Vous êtes sur la page 1sur 20

IU-VNU-HCM

LOGO

Data Structures and Algorithms


Robert Lafore, Data structures and Algorithms in Java, Waite Group Press, 2002

Lecture 6. Recursion

Trong Hai Duong, PhD


Email: haiduongtrong@gmail.com
Mobile phone: 0945090908
Homepage: http://co-intelligence.vn

2/28

Contents
What is Recursion?
A programming technique in which a method
(function) calls itself
Contents
Triangular Numbers
Factorials
A Recursive Binary Search
The Towers of Hanoi
Mergesort

3/28

Triangular Numbers: Examples

Finding nth Term using a Loop

4/28

Finding n

th

Term using Recursion


5/28

WHY?

Value of the nth term is the SUM of:


The first column (row): n
The SUM of the rest columns (rows)

Finding n Term using


Recursion
th

Now, it is complete with


stopping condition

See triangle.java program

6/28

Recursion Characteristics

7/28

It calls itself
When it calls itself, it does so to solve a
smaller problem
There is some version of the problem
that is simple enough that the routine
can solve it, and return, without calling
itself
Is recursion efficient?
No
Address of calling methods must be remembered
(in stack)
Intermediate arguments must also be stored

Factorials

8/28

Binary Search: Recursion vs. Loop


9/28

Assumption: Sorted Array


LOOP

RECURSION
See binarySearch.java

10/28

11/28

Divide-and-conquer
Divide problems into two halves
Solve each one separately
A recursive call is usually used for each half
Can be non-recursive
Examples
The Towers of Hanoi
MergeSort

Towers of Hanoi

12/28

See Towers Workshop Applet

An ancient puzzle consisting of a


number of disks placed on three
columns (A, B, C)
Objectives
Transfer all disks from column A to column C
Rules
Only one disk can be moved at a time
No disk can be placed on a disk that is
smaller than itself

Recursive Algorithm

See towers.java

13/28

14/28

Merge Sort
Simple Sorting Algorithms: O(N2)
Bubble Sort, Selection Sort, Insertion Sort
Using Sorted Linked List
MergeSort: O(NlogN)
Approach to MergeSort
Merging Two Sorted Arrays
Sorting by Merging
Demo via Workshop Applet
Efficiency of MergeSort

two
sorted
Given two sorted arrays
arrays
(A, B)

15/28

Creating sorted array C


containing all
elements of A, B
See merge.java

Merge Sort
Devide an array in
halves
Sort each half
Using recursion
Divide half into quarters
Sort each of the quarters
Merge them to make a
sorted half

Call merge() to merge


two halves into a
single sorted array
See Workshop Applet
See mergeSort.java

16/28

17/28

Array with one


element is
SORTED!

18/28

Efficiency of Merge
Sort: O(NlogN)

19/28

Number of Copies

Copied to Workspace
Copied back to
original array

NEX
T

Efficiency of Merge Sort: O(NlogN)


20/28

Vous aimerez peut-être aussi