Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.

Slides:



Advertisements
Similar presentations
CSC 205 Programming II Lecture 10 Towers of Hanoi.
Advertisements

Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Topic 14 Searching and Simple Sorts "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The.
Starting Out with Java: From Control Structures through Objects
Introduction to Recursion and Recursive Algorithms
Linear vs Binary Search COP What is recursion? // Pre-conditions: exponent is >= to 0 // Post-conditions: returns base exponent int Power(int base,
MATH 224 – Discrete Mathematics
CSE Lecture 3 – Algorithms I
More on Recursion More techniques 1. Binary search algorithm Binary searching for a key in an array is similar to looking for a word in dictionary Take.
Recursion.  Understand how the Fibonacci series is generated  Recursive Algorithms  Write simple recursive algorithms  Analyze simple recursive algorithms.
COSC 2006 Data Structures I Recursion III
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Factorial Recursion stack Binary Search Towers of Hanoi
Recursion CSC 220: Data Structure Winter Introduction A programming technique in which a function calls itself. One of the most effective techniques.
Recursion Chapter 7. Spring 2010CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
CMPT 225 Recursion-part 3. Recursive Searching Linear Search Binary Search Find an element in an array, return its position (index) if found, or -1 if.
Recursion. Recursive Solutions Recursion breaks a problem into smaller identical problems – mirror images so to speak. By continuing to do this, eventually.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors.
Main Index Contents 11 Main Index Contents Selection Sort Selection SortSelection Sort Selection Sort (3 slides) Selection Sort Alg. Selection Sort Alg.Selection.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
COMPSCI 105 S Principles of Computer Science Recursion 3.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Recursion.  Identify recursive algorithms  Write simple recursive algorithms  Understand recursive function calling  With reference to the call stack.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursion: The Mirrors Chapter 2.
Recursion: The Mirrors Chapter 2 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© 2006 Pearson Addison-Wesley. All rights reserved 3-1 Chapter 3 Recursion: The Mirrors.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursion: The Mirrors Chapter 2.
Chapter 3 Recursion: The Mirrors. © 2004 Pearson Addison-Wesley. All rights reserved 3-2 Recursive Solutions Recursion –An extremely powerful problem-solving.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
CSC 211 Data Structures Lecture 13
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
By: Lokman Chan Recursive Algorithm Recursion Definition: A function that is define in terms of itself. Goal: Reduce the solution to.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
CMPT 225 Recursion. Objectives Understand how the Fibonacci series is generated Recursive Algorithms  Write simple recursive algorithms  Analyze simple.
Data Structure and Algorithms. Algorithms: efficiency and complexity Recursion Reading Algorithms.
Chapter 8 Sorting and Searching Goals: 1.Java implementation of sorting algorithms 2.Selection and Insertion Sorts 3.Recursive Sorts: Mergesort and Quicksort.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Towers of Hanoi Move n (4) disks from pole A to pole B such that a larger disk is never put on a smaller disk A BC ABC.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Algorithm Analysis 1.
Towers of Hanoi Move n (4) disks from pole A to pole C
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Algorithm design and Analysis
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC

ABC Move n (4) disks from A to C Move n-1 (3) disks from A to B Move 1 disk from A to C Move n-1 (3) disks from B to C

Figure 2.19a and b a) The initial state; b) move n - 1 disks from A to C

Figure 2.19c and d c) move one disk from A to B; d) move n - 1 disks from C to B

Hanoi towers public static void solveTowers(int count, char source, char destination, char spare) { if (count == 1) { System.out.println("Move top disk from pole " + source + " to pole " + destination); } else { solveTowers(count-1, source, spare, destination); // X solveTowers(1, source, destination, spare); // Y solveTowers(count-1, spare, destination, source); // Z } // end if } // end solveTowers

Recursion tree: The order of recursive calls that results from solveTowers(3,A,B,C)

ABC ABC ABC Figure 2.21a Box trace of solveTowers(3, A, B, C) ABC

Figure 2.21b Box trace of solveTowers(3, A, B, C) ABC ABC ABC ABC

Figure 2.21c Box trace of solveTowers(3, A, B, C) ABC ABC ABC ABC

Figure 2.21d Box trace of solveTowers(3, A, B, C) ABC

Figure 2.21e Box trace of solveTowers(3, A, B, C)

Cost of Hanoi Towers How many moves is necessary to solve Hanoi Towers problem for N disks? moves(1) = 1 moves(N) = moves(N-1) + moves(1) + moves(N-1) i.e. moves(N) = 2*moves(N-1) + 1 Guess solution and show its correct with Mathematical Induction!

Recursive Searching Linear Search Binary Search Find an element in an array, return its position (index) if found, or -1 if not found.

Linear Search Algorithm (Java) public int linSearch(int[] arr, int target) { for (int i=0; i<arr.size; i++) { if (target == arr[i]) { return i; } } //for return -1; //target not found }

Linear Search Iterate through an array of n items searching for the target item The crucial instruction is equality checking (or comparisons for short) x.equals(arr[i]); //for objects or x == arr[i]; //for a primitive type Linear search performs at most n comparisons We can write linear search recursively

Recursive Linear Search Algorithm public int recLinSearch(int[] arr,int low,int x) { if (low >= arr.length) { // reach the end return -1; } else if (x == arr[low]){ return low; } else return recLinSearch(arr, low + 1, x); } Base case Found the target or Reached the end of the array Recursive case Call linear search on array from the next item to the end

Binary Search Sketch Linear search runs in O(n) (linear) time (it requires n comparisons in the worst case) If the array to be searched is sorted (from lowest to highest), we can do better: Check the midpoint of the array to see if it is the item we are searching for Presumably there is only a 1/n chance that it is! (assuming that the target is in the array) It the value of the item at the midpoint is less than the target then the target must be in the upper half of the array So perform binary search on that half and so on ….

Thinking About Binary Search Each sub-problem searches an array slice (or subarray) So differs only in the upper and lower array indices that define the array slice Each sub-problem is smaller than the previous problem In the case of binary search, half the size The final problem is so small that it is trivial Binary search terminates after the problem space consists of one item or When the target item is found Be careful when writing the terminating condition When exactly do we want to stop? When the search space consists of one element but Only after that one element has been tested

Recursive Binary Search Algorithm public int binSearch( int[] arr, int lower, int upper, int x) { int mid = (lower + upper) / 2; if (lower > upper) {// empty interval return - 1; // base case } else if(arr[mid] == x){ return mid; // second base case } else if(arr[mid] < x){ return binSearch(arr, mid + 1, upper, x); } else { // arr[mid] > target return binSearch(arr, lower, mid - 1, x); }

Analyzing Binary Search Best case: 1 comparison Worst case: target is not in the array, or is the last item to be compared Each recursive call halves the input size Assume that n = 2 k (e.g. if n = 128, k = 7) After the first iteration there are n/2 candidates After the second iteration there are n/4 (or n/2 2 ) candidates After the third iteration there are n/8 (or n/2 3 ) candidates After the k-th iteration there is one candidate because n/2 k = 1 Because n = 2 k, k = log 2 n Thus, at most k=log 2 n recursive calls are made in the worst case!

Binary Search vs Linear Search N Linear N Binary log 2 (N) , , , ,000, ,000,000 24

Iterative Binary Search Use a while loop instead of recursive calls The initial values of lower and upper do not need to be passed to the method but Can be initialized before entering the loop with lower set to 0 and upper to the length of the array-1 Change the lower and upper indices in each iteration Use the (negation of the) base case condition as the condition for the loop in the iterative version. Return a negative result if the while loop terminates without finding the target

Binary Search Algorithm (Java) public int binSearch(int[] arr, int target){ int lower = 0; int upper = arr.length - 1; while (lower <= upper){ int mid = (lower + upper) / 2; if (target == arr[mid]) { return mid; } else if (target > arr[mid]) { lower = mid + 1; } else { //target < arr[mid] upper = mid - 1; } } //while return -1; //target not found } Index of the first and last elements in the array

Recursion Disadvantage 1 Recursive algorithms have more overhead than similar iterative algorithms Because of the repeated method calls (storing and removing data from call stack) This may also cause a stack overflow when the call stack gets full It is often useful to derive a solution using recursion and implement it iteratively Sometimes this can be quite challenging! (Especially, when computation continues after the recursive call -> we often need to remember value of some local variable -> stacks can be often used to store that information.)

Recursion Disadvantage 2 Some recursive algorithms are inherently inefficient An example of this is the recursive Fibonacci algorithm which repeats the same calculation again and again Look at the number of times fib(2) is called Even if the solution was determined using recursion such algorithms should be implemented iteratively To make recursive algorithm efficient: Generic method (used in AI): store all results in some data structure, and before making the recursive call, check whether the problem has been solved. Make iterative version.

Function Analysis for call fib(5) fib(5) fib(4) fib(3) fib(2) fib(1)fib(0)fib(2) fib(1)fib(0) fib(1) fib(2) fib(1)fib(0) fib(1) public static int fib(int n) if (n == 0 || n == 1) return n else return fib(n-1) + fib(n-2)