CS171 Introduction to Computer Science II Recursion Li Xiong - - PowerPoint PPT Presentation

cs171 introduction to computer science ii
SMART_READER_LITE
LIVE PREVIEW

CS171 Introduction to Computer Science II Recursion Li Xiong - - PowerPoint PPT Presentation

CS171 Introduction to Computer Science II Recursion Li Xiong 2/28/2012 1 What we have learned so far Basic data structure Arrays Linked list Abstract data types Abstract data types Stacks Queues Linked List A


slide-1
SLIDE 1

CS171 Introduction to Computer Science II

2/28/2012 1

Recursion

Li Xiong

slide-2
SLIDE 2

What we have learned so far

Basic data structure

Arrays Linked list

Abstract data types Abstract data types

Stacks Queues

slide-3
SLIDE 3

Linked List

A Linked List is a sequence of nodes chained together. Each node, element, or link contains a data item, and a reference to next node

slide-4
SLIDE 4

Stacks and Queues

Can be implemented by both (resizing) arrays and linked list

slide-5
SLIDE 5

Today

Quiz on stacks, queues, linked list Recursion

slide-6
SLIDE 6

Recursion

Recursion concept Examples

Factorial Fibonacci GCD GCD Recursive graph Htree

Next lecture

Divide and conquer Binary search Tower of Hanoi Cost analysis of recursive algorithms

slide-7
SLIDE 7

2/28/2012 7

slide-8
SLIDE 8

What is recursion?

slide-9
SLIDE 9
slide-10
SLIDE 10

Factorial

N! = N*(N-1)*(N-2)*…..* 2 * 1

slide-11
SLIDE 11

Recursive Method

A method that calls itself (direct recursion)

slide-12
SLIDE 12

Recursive Method

A method that calls itself (direct recursion) Every recursive method must have a base case that is not recursive

slide-13
SLIDE 13

Better version of recursion definition

Recursion

  • n. If you still don't get

it, see Recursion.

slide-14
SLIDE 14

Recursion

A method calls itself

Calls a “clone” of itself to solve a smaller problem Buck Passing

Must have a base case Must have a base case

The buck stops here! (does not call the method)

slide-15
SLIDE 15

Example: Fibonacci Numbers

Recursive formula:

= −+ − = =

0, 1, 1, 2, 3, 5, 8, 13, …..

slide-16
SLIDE 16

Fibonacci Numbers: Java Code

slide-17
SLIDE 17
slide-18
SLIDE 18
slide-19
SLIDE 19
slide-20
SLIDE 20
slide-21
SLIDE 21

Visual Recursion

slide-22
SLIDE 22

Fractals

2/28/2012 22

slide-23
SLIDE 23
slide-24
SLIDE 24
slide-25
SLIDE 25
slide-26
SLIDE 26
slide-27
SLIDE 27

Recursion

Recursive method Examples

Factorial Fibonacci GCD GCD Recursive graph Htree

Next lecture

Divide and conquer Binary search Tower of Hanoi Cost analysis of recursive algorithms