The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!



Similar documents
csci 210: Data Structures Recursion

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Algorithms. Margaret M. Fleck. 18 October 2010

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

10CS35: Data Structures Using C

Section IV.1: Recursive Algorithms and Recursion Trees

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Converting a Number from Decimal to Binary

6. Standard Algorithms

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

CSE 326, Data Structures. Sample Final Exam. Problem Max Points Score 1 14 (2x7) 2 18 (3x6) Total 92.

Lecture Notes on Linear Search

Pseudo code Tutorial and Exercises Teacher s Version

Analysis of Binary Search algorithm and Selection Sort algorithm

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Computer Science 210: Data Structures. Searching

Data Structures and Algorithms Written Examination

Algorithm Design and Recursion

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Binary Heap Algorithms

Analysis of a Search Algorithm

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Many algorithms, particularly divide and conquer algorithms, have time complexities which are naturally

Chapter 13: Query Processing. Basic Steps in Query Processing

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Analysis of Algorithms I: Optimal Binary Search Trees

Module 2 Stacks and Queues: Abstract Data Types

Recursion and Recursive Backtracking

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Sample Questions Csci 1112 A. Bellaachia

Introduction to Algorithms March 10, 2004 Massachusetts Institute of Technology Professors Erik Demaine and Shafi Goldwasser Quiz 1.

Ordered Lists and Binary Trees

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Binary Search Trees (BST)

recursion, O(n), linked lists 6/14

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

CS473 - Algorithms I

Biostatistics 615/815

Lecture Notes on Binary Search Trees

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Basic Programming and PC Skills: Basic Programming and PC Skills:

Regression Verification: Status Report

Dynamic Programming. Lecture Overview Introduction

To My Parents -Laxmi and Modaiah. To My Family Members. To My Friends. To IIT Bombay. To All Hard Workers

Algorithm Analysis [2]: if-else statements, recursive algorithms. COSC 2011, Winter 2004, Section N Instructor: N. Vlajic

Binary Search Trees CMPSC 122

MATH 289 PROBLEM SET 4: NUMBER THEORY

Data Structures. Algorithm Performance and Big O Analysis

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Data Structures and Algorithms

DATA STRUCTURES USING C

Figure 1: Graphical example of a mergesort 1.

Solving Problems Recursively

HW4: Merge Sort. 1 Assignment Goal. 2 Description of the Merging Problem. Course: ENEE759K/CMSC751 Title:

Closest Pair Problem

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

LINKED DATA STRUCTURES

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Sorting Algorithms. Nelson Padua-Perez Bill Pugh. Department of Computer Science University of Maryland, College Park

Intermediate Math Circles March 7, 2012 Linear Diophantine Equations II

Lecture Notes on Binary Search Trees

CS 2412 Data Structures. Chapter 2 Stacks and recursion

Dynamic Programming Problem Set Partial Solution CMPSC 465

1 Description of The Simpletron

Grade 6 Math Circles March 10/11, 2015 Prime Time Solutions

Recursion and Dynamic Programming. Biostatistics 615/815 Lecture 5

CS 103X: Discrete Structures Homework Assignment 3 Solutions

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Data Structures. Level 6 C Module Descriptor

Heaps & Priority Queues in the C++ STL 2-3 Trees

Data Structures and Data Manipulation

3.5 RECURSIVE ALGORITHMS

Chapter 5. Recursion. Data Structures and Algorithms in Java

Symbol Tables. Introduction

PES Institute of Technology-BSC QUESTION BANK

Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

External Sorting. Chapter 13. Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 1

Binary search algorithm

Mathematical Induction. Lecture 10-11

TREE BASIC TERMINOLOGIES

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

AP Computer Science AB Syllabus 1

Recursive Algorithms. Recursion. Motivating Example Factorial Recall the factorial function. { 1 if n = 1 n! = n (n 1)! if n > 1

CSE 326: Data Structures B-Trees and B+ Trees

Lecture 13 - Basic Number Theory.

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Lecture 12 Doubly Linked Lists (with Recursion)

CompSci-61B, Data Structures Final Exam

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

Motivation Suppose we have a database of people We want to gure out who is related to whom Initially, we only have a list of people, and information a

Outline BST Operations Worst case Average case Balancing AVL Red-black B-trees. Binary Search Trees. Lecturer: Georgy Gimel farb

Transcription:

The Tower of Hanoi Recursion Solution recursion recursion recursion Recursive Thinking: ignore everything but the bottom disk. 1 2 Recursive Function Time Complexity Hanoi (n, src, dest, temp): If (n > 0) then Hanoi (n -1, src, temp, dest) Move disk n from src to dest Hanoi (n -1, temp, dest, src) T(n): time to move n disks via recursive algorithm T(n) = 2T(n-1)+1 n > 1 and T(1) = 1 3 4 Why Recursion? Recursive Thinking Examples: Recursive Definitions of Mathematical Formulas Factorial Powers Greatest common divisor Practical example: Directory Search! Recursion splits a problem: Into one or more simpler versions of itself E.g. n! = n* (n-1)! x n = x * x n-1 5 6 1

Simple Example: Factorial Recall from math that factorial is defined as 0! = 1 n! = n* (n-1)! where n is not negative. Base Case Recursive Case Implementation int factorial(int N) { if (N == 0) return 1; Base Case return N*factorial(N-1); Recursive Case 7 8 A simple definition of recursion General Recursive Design Strategy Recursion simply means a function that calls itself. In order to keep the recursion from going on forever, you must make sure you hit a termination condition called the base case. Identify the base case(s) (for direct solution). Devise a problem splitting strategy. Subproblems must be smaller. Subproblems must work towards a base case. Devise a solution combining strategy. 9 10 Outline of a Recursive Function Recursive Definitions of Mathematical Formulas if (answer is known) provide the answer else make a recursive call to solve a smaller version of the same problem Base case Recursive case Mathematicians often use recursive definitions. These lead naturally to recursive algorithms. Examples include: Factorial Powers Greatest common divisor 11 12 2

Example: Factorial How Recursion Works int factorial(int N) { if (N == 0) return 1; Base Case return N*factorial(N-1); Recursive Case A recursive function call is handled like any other function call. Each recursive call has an activation record on the stack. Stores values of parameters and local variables. When base case is reached return is made to previous call - the recursion unwinds. 13 14 Example: Trace Factorial(3) n! = n * (n-1)! 0! = 1 If a recursive function never reaches its base case, a stack overflow error occurs. Recursive Definitions: Power x 0 = 1 x n = x *x n-1 public static double power (double x, int n) { if (n == 0) return 1; else return x * power(x, n-1); 15 16 Greatest Common Divisor Recursion Vs. Iteration Definition of gcd(m, n), for integers m > n > 0: gcd(m, n) = n, if n divides m evenly gcd(m, n) = gcd(n, m % n), otherwise public static int gcd (int m, int n) { if (m < n) return gcd(n, m); else if (m % n == 0) return n; else return gcd(n, m % n); Recursion and iteration are similar. Iteration: Loop repetition test determines whether to exit. Recursion: Condition tests for a base case. Can always write iterative solution to a problem solved recursively, but: Recursive code often simpler than iterative. Thus easier to write, read, and debug. 17 18 3

Factorial (n) - iterative Factorial (n) = n * (n-1) * (n-2) *... * 1 for n > 0 Factorial (0) = 1 int IterFactorial (int n) { int fact =1; for (int i = 1; i <= n; i++) fact = fact * i; return fact; Efficiency of Recursion Recursive method often slowerthan iterative; why? Overhead for loop repetition smaller than overhead for call and return. 19 20 Recursive Data Structures Recursive Data Structures Just as we have recursive algorithms. We can have recursive data structures. Like algorithms, a recursive data structure has: A base case, a simple data structure, or null A recursive case: includes a smallerinstance of the same data structure. Computer scientists often definedata structures recursively. Trees are defined recursively. Linked lists can also be defined recursively. Recursive methods are very natural in processing recursive data structures. 21 22 Recursive Definition of Linked List A linked list is either: An empty list the base case, or A head node, consisting of: recursive case A data itemand A reference to a linked list(rest of list) Divide-and-Conquer The most-well known algorithm design strategy: Divide instance of problem into two or more smaller instances Solve smaller instances recursively Obtain solution to original (larger) instance by combining these solutions 23 24 4

Divide-and-Conquer Technique Divide-and-Conquer Examples subproblem 1 of size n/2 a problem of size n (instance) subproblem 2 of size n/2 Binary search (?) Sorting: mergesort and quicksort Binary tree traversals a solution to subproblem 1 a solution to subproblem 2 a solution to the original problem It general leads to a recursive algorithm! 25 26 Binary Search Very efficient algorithm for searching in a sorted array: K vs A[0]... A[m]... A[n-1] If K = A[m], stop (successful search); otherwise, continue searching by the same method in A[0..m-1] if K < A[m] and in A[m+1..n-1] if K > A[m] Binary Search Time efficiency: worst-case recurrence: T (n) = 1 + T( n/2 ), T (1) = 1 solution: T(n) = log 2 (n+1) Optimal for searching a sorted array Limitations: must be a sorted array (not linked list) 27 28 Merge-Sort Pseudocode of Mergesort Merge-sort on an input sequence Swith nelements consists of three steps: Divide: partition Sinto two sequences S 1 and S 2 of about n/2 elements each Recur: recursively sort S 1 and S 2 Conquer: merge S 1 and S 2 into a unique sorted sequence 29 30 5

Pseudocode of Merge Mergesort Example 3 8 2 9 1 7 4 5 2 3 8 9 1 4 5 7 Time complexity: O(p+q) = O(n) comparisons 31 1 2 3 4 5 7 8 9 32 Analysis of Mergesort Time Complexity Merge sort has an average and worst-case performance: O(n log n) T(1) =1 Space requirement: O(n) 33 34 6