Académique Documents
Professionnel Documents
Culture Documents
LOGO
Lecture 6. Recursion
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
4/28
Finding n
th
WHY?
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
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
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
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
16/28
17/28
18/28
Efficiency of Merge
Sort: O(NlogN)
19/28
Number of Copies
Copied to Workspace
Copied back to
original array
NEX
T