Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Size: px
Start display at page:

Download "Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages"

Transcription

1 Recursion Solution Counting Things Searching an Array Organizing Data Backtracking Defining Languages 1

2 Recursion Solution 3 RECURSION SOLUTION Recursion An extremely powerful problem-solving technique Breaks a problem in smaller identical problems An alternative to iteration o An iterative solution involves loops Some recursion solutions are inefficient and impractical 2

3 RECURSION SOLUTION Looking up a word in a dictionary Sequential search o Starts at the beginning of the collection o Looks at every item in the collection in order until the item being searched for is found Binary search o Repeatedly halves the collection and determines which half could contain the item o Uses a divide and conquer strategy Search dictionary Search first half of dictionary Search second half of dictionary RECURSION SOLUTION Facts about a recursive solution search (in thedictionary:dictionary, in aword:string) { if(thedictionary is one page in size){ scan the page for aword else{ Open the Dictionary to a point near the middle Determine which half of the thedictionary contains aword if(aword is in the first half){ search(first half of thedictionary, aword) else{ search(second half of thedictionary, aword) one of the smaller problems must be the base case A test for the base case enables the recursive calls to stop A recursive method calls itself Each recursive call solves an identical, but smaller, problem 3

4 RECURSION SOLUTION Four questions for construction recursive solutions How can you define the problem in terms of a smaller problem of the same type? How does each recursive call diminish the size of the problem? What instance of the problem can serve as the base case? As the problem size diminishes, will you reach this base case? RECURSION SOLUTION A Recursive Valued Method: The Factorial of n Problem o Compute the factorial of an integer n An iterative definition of factorial(n) factorial(n) = n * (n-1) * (n-2) * * 1 for any integer n > 0 factorial(0) = 1 A recursive definition of factorial(n) factorial(n) = 1 if n = 0 n * factorial(n-1) if n > 0 4

5 RECURSION SOLUTION A Recursive Valued Method: The Factorial of n public static int fact (int n){ // //precondition: n must be greater than or equal to 0 //postcondition: returns the factorial of n // if(n==0){ return 1; else{ return n*fact(n-1); RECURSION SOLUTION Box trace A systematic way to trace the actions of a recursive method Each box roughly corresponds to an activation record An activation record o Contains a method s local environment at the time of calling and as a result of the call to the method A method s local environment includes: o The method s local variables o A copy of the actual value arguments o A return address in the calling routine o The value of the method itself System.out.println(fact(3)); 5

6 RECURSION SOLUTION A Recursive void Method: Writing a String Backward Problem o Given a string of characters, write it in reverse order Recursive solution o Each recursive step of the solution diminishes by 1 the length of the string to be written backward Base case o Write the empty string backward Recursively: o Strip away the last character or the first character RECURSION SOLUTION A Recursive void Method: Writing a String Backward Strip away the last character or the first character writebackward (in s:string){ if(the string s is empty){ Do nothing else{ writebackward(s the last character minus of its s first character) writebackward(s the first character minus of its s last character) 6

7 Counting Things 13 COUNTING THINGS Next three problems Require you to count certain events or combinations of events or things Contain more than one base cases Are good examples of inefficient recursive solutions 7

8 COUNTING THINGS Multiplying Rabbits (The Fibonacci Sequence) Facts about rabbits o Rabbits never die o A rabbit reaches sexual maturity exactly two months after birth, that is, at the beginning of its third month of life o Rabbits are always born in male-female pairs Problem At the beginning of every month, each sexually mature male-female pair gives birth to exactly one male-female pair o How many pairs of rabbits are alive in month n? Recursive definition rabbit(n) = 1 if n is 1 or 2 rabbit(n-1) + rabbit(n-2) if n > 2 COUNTING THINGS Multiplying Rabbits (The Fibonacci Sequence) 8

9 COUNTING THINGS Organizing a Parade Rules about organizing a parade o The parade will consist of bands and floats in a single line o One band cannot be placed immediately after another Problem o How many ways can you organize a parade of length n? COUNTING THINGS Organizing a Parade Let: o P(n) be the number of ways to organize a parade of length n o F(n) be the number of parades of length n that end with a float o B(n) be the number of parades of length n that end with a band o Then, P(n) = F(n) + B(n) Number of acceptable parades of length n that end with a float F(n) = P(n-1) Number of acceptable parades of length n that end with a band B(n) = F(n-1) Number of acceptable parades of length n P(n) = P(n-1) + P(n-2) 9

10 COUNTING THINGS Organizing a Parade Base cases o P(1) = 2 (The parades of length 1 are float and band.) o P(2) = 3 (The parades of length 2 are float-float, band-float, and float-band.) Solution o P(1) = 2 o P(2) = 3 o P(n) = P(n-1) + P(n-2) for n > 2 COUNTING THINGS Mr. Spock s Dilemma (Choosing k out of n Things) Problem o How many different choices are possible for exploring k planets out of n planets in a solar system? o Let c(n, k) be the number of groups of k planets chosen from n In terms of Planet X: o c(n, k) = (the number of groups of k planets that include Planet X) + (the number of groups of k planets that do not include Planet X) o c(n, k) = c(n-1, k-1) + c(n-1, k) Recursive solution 1 if k = 0 c(n, k) = 1 if k = n 0 if k > n c(n-1, k-1) + c(n-1, k) if 0 < k < n 10

11 COUNTING THINGS Mr. Spock s Dilemma (Choosing k out of n Things) Searching an Array 22 11

12 SEARCHING AN ARRAY A high-level binary search binarysearch(in anarray:arraytype, in value:itemtype){ if (anarray is of size 1) { Determine if anarray s item is equal to value else { Find the midpoint of anarray Determine which half of anarray contains value if (value is in the first half of anarray) { binarysearch (first half of anarray, value) else { binarysearch(second half of anarray, value) // end if // end if SEARCHING AN ARRAY A high-level binary search Implementation issues: o How will you pass half of anarray to the recursive calls to binarysearch? o How do you determine which half of the array contains value? o What should the base case(s) be? Given value is in or not in the array o How will binarysearch indicate the result of the search? 12

13 SEARCHING AN ARRAY Finding the k th Smallest Item in an Array The recursive solution proceeds by: 1. Selecting a pivot item in the array 2. Cleverly arranging, or partitioning, the items in the array about this pivot item 3. Recursively applying the strategy to one of the partitions SEARCHING AN ARRAY Finding the k th Smallest Item in an Array Let: ksmall(k, anarray, first, last) = k th smallest item in anarray[first..last] Solution: ksmall(k, anarray, first, last) ksmall(k, anarray, first, pivotindex-1) if k < pivotindex first + 1 = p if k = pivotindex first + 1 ksmall(k-(pivotindex-first+1), anarray, pivotindex+1, last) if k >pivotindex first+ 1 13

14 Organizing Data 28 ORGANIZING DATA The Towers of Hanoi The emperor s puzzle: n disks and three poles o A (the source), B (the destination), and C (the spare) o The disks were of different sizes and had holes in the middle o The disks could be placed only on top of disks larger than themselves o Initially, all the disks were on pole A o The puzzle was to move the disks, one by one, from pole A to pole B. 14

15 ORGANIZING DATA The Towers of Hanoi ORGANIZING DATA The Towers of Hanoi Pseudocode solution solvetowers(count, source, destination, spare) if (count is 1) { Move a disk directly from source to destination else { solvetowers(count-1, source, spare, destination) solvetowers(1, source, destination, spare) solvetowers(count-1, spare, destination, source) //end if 15

16 ORGANIZING DATA The Towers of Hanoi Recursion and Efficiency 33 16

17 RECURSION AND EFFICIENCY Recursion powerful-solving technique that often produces very clean solutions to even the most complex problems. Simple, short implementation Some recursive solutions are so inefficient that they should not be used Factors that contribute to the inefficiency of some recursive solutions Overhead associated with method calls Inherent inefficiency of some recursive algorithms Backtracking 35 17

18 BACKTRACKING Backtracking Considering an organized way to make successive guesses at a solution. If a particular guess leads to a dead end, you back up to that guess and replace it with a different guess. A strategy for guessing at a solution and backing up when an impasse is reached BACKTRACKING The Eight Queens Problem Problem o Place eight queens on the chessboard so that no queen can attack any other queen Strategy: guess at a solution There are C(64,8) = 4,426,165,368 ways to arrange 8 queens on a chessboard of 64 squares An observation that eliminates many arrangements from consideration o No queen can reside in a row or a column that contains another queen Now: only 8!=40,320 arrangements of queens to be checked for attacks along diagonals 18

19 BACKTRACKING The Eight Queens Problem Providing organization for the guessing strategy o Place queens one column at a time o If you reach an impasse, backtrack to the previous column BACKTRACKING The Eight Queens Problem A recursive algorithm that places a queen in a column Base case o If there are no more columns to consider You are finished Recursive step o If you successfully place a queen in the current column Consider the next column o If you cannot place a queen in the current column You need to backtrack 19

20 Defining Language 40 DEFINING LANGUAGE Two Simple Languages: Palindromes A string that reads the same from left to right as it does from right to left Examples: radar, deed Language o Palindromes = {w : w reads the same left to right as right to left Grammar o < pal > = empty string < ch > a < pal > a b < pal > b Z < pal > Z o < ch > = a b z A B Z 20

21 DEFINING LANGUAGE Two Simple Languages: Palindromes Recognition algorithm ispal(w) if (w is the empty string or w is of length 1) { return true else if (w s first and last characters are the same letter ) { return ispal(w minus its first and last characters) else { return false DEFINING LANGUAGE Two Simple Languages: Strings of the form A n B n The string that consists of n consecutive A s followed by n consecutive B s Language o L = {w : w is of the form A n B n for some n 0 Grammar o < legal-word > = empty string A < legal-word > B 21

22 DEFINING LANGUAGE Two Simple Languages: Strings of the form A n B n Recognition algorithm isanbn(w) if (the length of w is zero) { return true else if (w begins with the character A and ends with the character B) { return isanbn(w minus its first and last characters) else { return false DEFINING LANGUAGE Two Simple Languages: Strings of the form A n B n Recognition algorithm isanbn(w) if (the length of w is zero) { return true else if (w begins with the character A and ends with the character B) { return isanbn(w minus its first and last characters) else { return false 22

23 DEFINING LANGUAGE Algebraic expression Infix expressions o An operator appears between its operands o Example: a + b*c Prefix expressions o An operator appears before its operands o Example: + a* bc Postfix expressions o An operator appears after its operands o Example: a bc* + DEFINING LANGUAGE Algebraic expression To convert a fully parenthesized infix expression to a prefix form o Move each operator to the position marked by its corresponding open parenthesis o Remove the parentheses Example o Infix expression: ((a + b) * c o Prefix expression: * + a b c 23

24 DEFINING LANGUAGE Algebraic expression To convert a fully parenthesized infix expression to a postfix form o Move each operator to the position marked by its corresponding closing parenthesis o Remove the parentheses Example o Infix form: ((a + b) * c) o Postfix form: a b + c * DEFINING LANGUAGE Algebraic expression To avoid ambiguity, infix notation normally requires o Precedence rules o Rules for association o Parentheses Prefix and postfix expressions o Never need Precedence rules Association rules Parentheses o Have Simple grammar expressions Straightforward recognition and evaluation algorithms 24

25 DEFINING LANGUAGE Algebraic expression Prefix expression o < prefix > = < identifier > < operator > < prefix > < prefix > o < operator > = + - * / o < identifier > = a b z Postfix expression o < postfix > = < identifier > < postfix > < postfix > < operator> o < operator > = + - * / o < identifier > = a b z Fully parenthesized expressions o < infix > = < identifier > (< infix > < operator > < infix > ) o < operator > = + - * / o < identifier > = a b z HOMEWORK Read through Chapter 3, Chapter 6 25

Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5

Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5 Chapter 5 Recursion as a Problem-Solving Technique Backtracking Backtracking A strategy for guessing at a solution and backing up when an impasse is reached Recursion and backtracking can be combined to

More information

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited Module 6 Recursion Revisited CS 147 Sam Houston State University Dr. McGuire Backtracking Backtracking A strategy for guessing at a solution and backing up when an impasse is reached Recursion and backtracking

More information

Chapter 2. Question 2 Write a box trace of the function given in Checkpoint Question 1. We trace the function with 4 as its argument (see next page).

Chapter 2. Question 2 Write a box trace of the function given in Checkpoint Question 1. We trace the function with 4 as its argument (see next page). Data Abstraction and Problem Solving with C++ Walls and Mirrors 7th Edition Carrano Solutions Manual Full Download: http://testbanklive.com/download/data-abstraction-and-problem-solving-with-c-walls-and-mirrors-7th-edition-carra

More information

Lecture Chapter 6 Recursion as a Problem Solving Technique

Lecture Chapter 6 Recursion as a Problem Solving Technique Lecture Chapter 6 Recursion as a Problem Solving Technique Backtracking 1. Select, i.e., guess, a path of steps that could possibly lead to a solution 2. If the path leads to a dead end then retrace steps

More information

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique.

What is Recursion? ! Each problem is a smaller instance of itself. ! Implemented via functions. ! Very powerful solving technique. Recursion 1 What is Recursion? Solution given in terms of problem. Huh? Each problem is a smaller instance of itself. Implemented via functions. Very powerful solving technique. Base Case and Recursive

More information

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano Chapter 2 Recursion: The Mirrors Multiple Choice Questions 1. In a recursive solution, the terminates the recursive processing. a) local environment b) pivot item c) base case d) recurrence relation 2.

More information

Recursion as a Problem-Solving Technique. Chapter 5

Recursion as a Problem-Solving Technique. Chapter 5 Recursion as a Problem-Solving Technique Chapter 5 Overview Ass2: TimeSpan Ass3: Maze "Quiz Ch02 + Ch05" - due before Wednesday class Not all in-class quizzes will be announced ahead of time Week-5: Sample

More information

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank Download link: https://solutionsmanualbank.com/download/test-bank-for-data-abstractionproblem-solving-with-c-walls-and-mirrors-6-e-carrano-henry/

More information

Programming with Recursion. What Is Recursion?

Programming with Recursion. What Is Recursion? Chapter 7 Programming with Recursion Fall 2017 Yanjun Li CS2200 1 What Is Recursion? How is recursion like a set of Russian dolls? Fall 2017 Yanjun Li CS2200 2 What Is Recursion? Recursive call A method

More information

Solving problems by recursion

Solving problems by recursion Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem into simpler problems Sometimes, the simpler problem is similar to (but smaller than)

More information

Recursion continued. Programming using server Covers material done in Recitation. Part 2 Friday 8am to 4pm in CS110 lab

Recursion continued. Programming using server Covers material done in Recitation. Part 2 Friday 8am to 4pm in CS110 lab Recursion continued Midterm Exam 2 parts Part 1 done in recitation Programming using server Covers material done in Recitation Part 2 Friday 8am to 4pm in CS110 lab Question/Answer Similar format to Inheritance

More information

8/22/12. Outline. Backtracking. The Eight Queens Problem. Backtracking. Part 1. Recursion as a Problem-Solving Technique

8/22/12. Outline. Backtracking. The Eight Queens Problem. Backtracking. Part 1. Recursion as a Problem-Solving Technique Part 1. Recursion as a Problem-Solving Technique CS 200 Algorithms and Data Structures CS 200 Algorithms and Data Structures [Fall 2011] 2 Outline Backtracking Formal grammars Relationship between recursion

More information

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling Recursion Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling With reference to the call stack Compute the result of simple recursive algorithms Understand

More information

1 Recursion. 2 Recursive Algorithms. 2.1 Example: The Dictionary Search Problem. CSci 235 Software Design and Analysis II Introduction to Recursion

1 Recursion. 2 Recursive Algorithms. 2.1 Example: The Dictionary Search Problem. CSci 235 Software Design and Analysis II Introduction to Recursion 1 Recursion Recursion is a powerful tool for solving certain kinds of problems. Recursion breaks a problem into smaller problems that are identical to the original, in such a way that solving the smaller

More information

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved Recursion Chapter 7 Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an Array Recursively Processing a Linked Chain The Time Efficiency

More information

Unit-2 Divide and conquer 2016

Unit-2 Divide and conquer 2016 2 Divide and conquer Overview, Structure of divide-and-conquer algorithms, binary search, quick sort, Strassen multiplication. 13% 05 Divide-and- conquer The Divide and Conquer Paradigm, is a method of

More information

Recursion: The Mirrors. (Walls & Mirrors - Chapter 2)

Recursion: The Mirrors. (Walls & Mirrors - Chapter 2) Recursion: The Mirrors (Walls & Mirrors - Chapter 2) 1 To iterate is human, to recurse, divine. - L. Peter Deutsch It seems very pretty but it s rather hard to understand! - Lewis Carroll 2 A recursive

More information

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Recursive Methods and Problem Solving Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Review: Calling Methods int x(int n) { int m = 0; n = n + m + 1; return n; int y(int

More information

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 4- Recursion What Is Recursion? Consider hiring a contractor to build He hires a subcontractor for a portion of the job That subcontractor hires a sub-subcontractor to do

More information

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO? 8/5/10 TODAY'S OUTLINE Recursion COMP 10 EXPLORING COMPUTER SCIENCE Revisit search and sorting using recursion Binary search Merge sort Lecture 8 Recursion WHAT DOES THIS CODE DO? A function is recursive

More information

www.thestudycampus.com Recursion Recursion is a process for solving problems by subdividing a larger problem into smaller cases of the problem itself and then solving the smaller, more trivial parts. Recursion

More information

DATA ABSTRACTION AND PROBLEM SOLVING WITH JAVA

DATA ABSTRACTION AND PROBLEM SOLVING WITH JAVA DATA ABSTRACTION AND PROBLEM SOLVING WITH JAVA WALLS AND MIRRORS First Edition Frank M. Carrano University of Rhode Island Janet J. Prichard Bryant College Boston San Francisco New York London Toronto

More information

CS200: Recursion and induction (recap from cs161)

CS200: Recursion and induction (recap from cs161) CS200: Recursion and induction (recap from cs161) Prichard Ch. 6.1 & 6.3 1 2 Backtracking n Problem solving technique that involves moves: guesses at a solution. n Depth First Search: in case of failure

More information

12/30/2013 S. NALINI,AP/CSE

12/30/2013 S. NALINI,AP/CSE 12/30/2013 S. NALINI,AP/CSE 1 UNIT I ITERATIVE AND RECURSIVE ALGORITHMS Iterative Algorithms: Measures of Progress and Loop Invariants-Paradigm Shift: Sequence of Actions versus Sequence of Assertions-

More information

Recursion. Recursion is: Recursion splits a problem:

Recursion. Recursion is: Recursion splits a problem: Recursion Recursion Recursion is: A problem solving approach, that can... Generate simple solutions to... Certain kinds of problems that... Would be difficult to solve in other ways Recursion splits a

More information

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Recursive Algorithms. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Recursive Algorithms CS 180 Sunil Prabhakar Department of Computer Science Purdue University Recursive Algorithms Within a given method, we are allowed to call other accessible methods. It is also possible

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows: STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The

More information

EE 368. Weeks 4 (Notes)

EE 368. Weeks 4 (Notes) EE 368 Weeks 4 (Notes) 1 Read Chapter 3 Recursion and Backtracking Recursion - Recursive Definition - Some Examples - Pros and Cons A Class of Recursive Algorithms (steps or mechanics about performing

More information

Functions and Recursion

Functions and Recursion Functions and Recursion CSE 130: Introduction to Programming in C Stony Brook University Software Reuse Laziness is a virtue among programmers Often, a given task must be performed multiple times Instead

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Recursion - Examples Kostas Alexis CS302 - Data Structures using C++ Topic: The Binary Search Kostas Alexis The Binary Search Assumes and exploits that the input

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #9 John Ridgway February 26, 2015 1 Recursive Definitions, Algorithms, and Programs Recursion in General In mathematics and computer science

More information

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,

Revision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted, [1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n

More information

This book is licensed under a Creative Commons Attribution 3.0 License

This book is licensed under a Creative Commons Attribution 3.0 License 6. Syntax Learning objectives: syntax and semantics syntax diagrams and EBNF describe context-free grammars terminal and nonterminal symbols productions definition of EBNF by itself parse tree grammars

More information

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1 RECURSION Chapter 5 Recursive Thinking Section 5.1 1 Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that are difficult

More information

University of the Western Cape Department of Computer Science

University of the Western Cape Department of Computer Science University of the Western Cape Department of Computer Science Algorithms and Complexity CSC212 Paper II Final Examination 13 November 2015 Time: 90 Minutes. Marks: 100. UWC number Surname, first name Mark

More information

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer

17/05/2018. Outline. Outline. Divide and Conquer. Control Abstraction for Divide &Conquer. Outline. Module 2: Divide and Conquer Module 2: Divide and Conquer Divide and Conquer Control Abstraction for Divide &Conquer 1 Recurrence equation for Divide and Conquer: If the size of problem p is n and the sizes of the k sub problems are

More information

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

CS 171: Introduction to Computer Science II. Stacks. Li Xiong CS 171: Introduction to Computer Science II Stacks Li Xiong Today Stacks operations and implementations Applications using stacks Application 1: Reverse a list of integers Application 2: Delimiter matching

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

Chapter 18 Recursion. Motivations

Chapter 18 Recursion. Motivations Chapter 18 Recursion CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox 1 Motivations Suppose you want to find all the files under a directory

More information

Recursion. Chapter 7

Recursion. Chapter 7 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 algorithms and methods for searching arrays To learn

More information

Recursive Definitions

Recursive Definitions Recursion Objectives Explain the underlying concepts of recursion Examine recursive methods and unravel their processing steps Explain when recursion should and should not be used Demonstrate the use of

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015

Stack Applications. Lecture 25 Sections Robb T. Koether. Hampden-Sydney College. Mon, Mar 30, 2015 Stack Applications Lecture 25 Sections 18.7-18.8 Robb T. Koether Hampden-Sydney College Mon, Mar 30, 2015 Robb T. Koether Hampden-Sydney College) Stack Applications Mon, Mar 30, 2015 1 / 34 1 The Triangle

More information

Structured Programming with C Wrap-up

Structured Programming with C Wrap-up Structured Programming with C Wrap-up Programming Paradigms Programming Paradigm : Defines how to think when you are programming. Way of approaching the task. Common Paradigms; Imperative : Describe all

More information

Algorithms COMBINATORIAL SEARCH. permutations backtracking counting subsets paths in a graph

Algorithms COMBINATORIAL SEARCH. permutations backtracking counting subsets paths in a graph COMBINATORIAL SEARCH Algorithms F O U R T H E D I T I O N permutations backtracking counting subsets paths in a graph R O B E R T S E D G E W I C K K E V I N W A Y N E Algorithms, 4 th Edition Robert Sedgewick

More information

Classic Data Structures Introduction UNIT I

Classic Data Structures Introduction UNIT I ALGORITHM SPECIFICATION An algorithm is a finite set of instructions that, if followed, accomplishes a particular task. All algorithms must satisfy the following criteria: Input. An algorithm has zero

More information

Recursion. Example R1

Recursion. Example R1 Recursion Certain computer problems are solved by repeating the execution of one or more statements a certain number of times. So far, we have implemented the repetition of one or more statements by using

More information

Lecture 8 Recursion. The Mirrors

Lecture 8 Recursion. The Mirrors Lecture 8 Recursion The Mirrors Lecture Outline Recursion: Basic Idea, Factorial Iteration versus Recursion How Recursion Works Recursion: How to More Examples on Recursion Printing a Linked List (in Reverse)

More information

Tribhuvan University Institute of Science and Technology Computer Science and Information Technology (CSC. 154) Section A Attempt any Two questions:

Tribhuvan University Institute of Science and Technology Computer Science and Information Technology (CSC. 154) Section A Attempt any Two questions: Tribhuvan University 2065 Bachelor Level/ First Year/ Second Semester/ Science Full Marks: 60 Computer Science and Information Technology (CSC. 154) Pass Marks: 24 (Data Structure and Algorithm) Time:

More information

Introduction to Computers & Programming

Introduction to Computers & Programming 16.070 Introduction to Computers & Programming Ada: Recursion Prof. Kristina Lundqvist Dept. of Aero/Astro, MIT Recursion Recursion means writing procedures and functions which call themselves. Recursion

More information

Sorting & Searching (and a Tower)

Sorting & Searching (and a Tower) Sorting & Searching (and a Tower) Sorting Sorting is the process of arranging a list of items into a particular order There must be some value on which the order is based There are many algorithms for

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU

Data Structures. Chapter 06. 3/10/2016 Md. Golam Moazzam, Dept. of CSE, JU Data Structures Chapter 06 1 Stacks A stack is a list of elements in which an element may be inserted or deleted only at one end, called the top of the stack. This means that elements are removed from

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

Recursion vs Induction

Recursion vs Induction Recursion vs Induction CS3330: Algorithms The University of Iowa 1 1 Recursion Recursion means defining something, such as a function, in terms of itself For example, let f(x) = x! We can define f(x) as

More information

Data Structures and Algorithms Notes

Data Structures and Algorithms Notes Data Structures and Algorithms Notes Notes by Winst Course taught by Dr. G. R. Baliga 256-400 ext. 3890 baliga@rowan.edu Course started: September 4, 2012 Last generated: December 18, 2013 Interfaces -

More information

Chapter 15: Recursion

Chapter 15: Recursion Chapter 15: Recursion Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 15 discusses the following main topics: Introduction to Recursion

More information

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II Recursive Algorithms Department of Computer Science University of Maryland, College Park Recursion Recursion is a strategy for solving problems A procedure that

More information

CSE 214 Computer Science II Recursion

CSE 214 Computer Science II Recursion CSE 214 Computer Science II Recursion Fall 2017 Stony Brook University Instructor: Shebuti Rayana shebuti.rayana@stonybrook.edu http://www3.cs.stonybrook.edu/~cse214/sec02/ Introduction Basic design technique

More information

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, Recursion public static long fib(int n) if (n

More information

Recursion vs Induction. CS3330: Algorithms The University of Iowa

Recursion vs Induction. CS3330: Algorithms The University of Iowa Recursion vs Induction CS3330: Algorithms The University of Iowa 1 Recursion Recursion means defining something, such as a function, in terms of itself For example, let f(x) = x! We can define f(x) as

More information

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1

DIVIDE & CONQUER. Problem of size n. Solution to sub problem 1 DIVIDE & CONQUER Definition: Divide & conquer is a general algorithm design strategy with a general plan as follows: 1. DIVIDE: A problem s instance is divided into several smaller instances of the same

More information

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5 Lesson 12: Recursion, Complexity, Searching and Sorting Modifications By Mr. Dave Clausen Updated for Java 1_5 1 Lesson 12: Recursion, Complexity, and Searching and Sorting Objectives: Design and implement

More information

Divide & Conquer. 2. Conquer the sub-problems by solving them recursively. 1. Divide the problem into number of sub-problems

Divide & Conquer. 2. Conquer the sub-problems by solving them recursively. 1. Divide the problem into number of sub-problems Divide & Conquer Divide & Conquer The Divide & Conquer approach breaks down the problem into multiple smaller sub-problems, solves the sub-problems recursively, then combines the solutions of the sub-problems

More information

1. (a) O(log n) algorithm for finding the logical AND of n bits with n processors

1. (a) O(log n) algorithm for finding the logical AND of n bits with n processors 1. (a) O(log n) algorithm for finding the logical AND of n bits with n processors on an EREW PRAM: See solution for the next problem. Omit the step where each processor sequentially computes the AND of

More information

Objectives. Recursion. One Possible Way. How do you look up a name in the phone book? Recursive Methods Must Eventually Terminate.

Objectives. Recursion. One Possible Way. How do you look up a name in the phone book? Recursive Methods Must Eventually Terminate. Objectives Recursion Chapter 11 become familiar with the idea of recursion learn to use recursion as a programming tool become familiar with the binary search algorithm as an example of recursion become

More information

Table of Contents. Chapter 1: Introduction to Data Structures... 1

Table of Contents. Chapter 1: Introduction to Data Structures... 1 Table of Contents Chapter 1: Introduction to Data Structures... 1 1.1 Data Types in C++... 2 Integer Types... 2 Character Types... 3 Floating-point Types... 3 Variables Names... 4 1.2 Arrays... 4 Extraction

More information

Recursion. Chapter 5

Recursion. Chapter 5 Recursion Chapter 5 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn

More information

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1 Some Applications of Stack Spring Semester 2007 Programming and Data Structure 1 Arithmetic Expressions Polish Notation Spring Semester 2007 Programming and Data Structure 2 What is Polish Notation? Conventionally,

More information

QUIZ. 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different?

QUIZ. 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different? QUIZ 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different? 1 QUIZ 3] What are the 4 fundamental types of algorithms used to manipulate arrays? 4] What control structure

More information

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series. Recursion The programs we have discussed so far have been primarily iterative and procedural. Code calls other methods in a hierarchical manner. For some problems, it is very useful to have the methods

More information

SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Recursion 2018W (Institute of Pervasive Computing, JKU Linz) PRINCIPLE OF SELF-REFERENCE Recursion: Describing something in a self-similar way. An elegant, powerful and simple way

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Formal Languages and Automata Theory, SS Project (due Week 14)

Formal Languages and Automata Theory, SS Project (due Week 14) Formal Languages and Automata Theory, SS 2018. Project (due Week 14) 1 Preliminaries The objective is to implement an algorithm for the evaluation of an arithmetic expression. As input, we have a string

More information

Bachelor Level/ First Year/ Second Semester/ Science Full Marks: 60 Computer Science and Information Technology (CSc. 154) Pass Marks: 24

Bachelor Level/ First Year/ Second Semester/ Science Full Marks: 60 Computer Science and Information Technology (CSc. 154) Pass Marks: 24 Prepared By ASCOL CSIT 2070 Batch Institute of Science and Technology 2065 Bachelor Level/ First Year/ Second Semester/ Science Full Marks: 60 Computer Science and Information Technology (CSc. 154) Pass

More information

CS 211: Recursion. Chris Kauffman. Week 13-1

CS 211: Recursion. Chris Kauffman. Week 13-1 CS 211: Recursion Chris Kauffman Week 13-1 Front Matter Today P6 Questions Recursion, Stacks Labs 13: Due today 14: Review and evals Incentive to attend lab 14, announce Tue/Wed End Game 4/24 Mon P6, Comparisons

More information

CS/CE 2336 Computer Science II

CS/CE 2336 Computer Science II S/E 2336 omputer Science II UT D Session 10 Recursion dapted from D Liang s Introduction to Java Programming, 8 th Ed 2 factorial(0) = 1; omputing Factorial factorial(n) = n*factorial(n-1); n! = n * (n-1)!

More information

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

Prefix/Infix/Postfix Notation

Prefix/Infix/Postfix Notation Prefix/Infix/Postfix Notation One commonly writes arithmetic expressions, such as 3 + 4 * (5-2) in infix notation which means that the operator is placed in between the two operands. In this example, the

More information

= otherwise W-4 W-1. Overview. CSE 142 Computer Programming I. Overview. Factorial Function

= otherwise W-4 W-1. Overview. CSE 142 Computer Programming I. Overview. Factorial Function CSE 14 Computer Programming I Recursion Overview Review Function calls in C Concepts Recursive definitions and functions Base and recursive cases Reading Read textbook sec. 10.1-10.3 & 10.7 Optional: sec.

More information

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

Recursion. Dr. Jürgen Eckerle FS Recursive Functions Recursion Dr. Jürgen Eckerle FS 2008 Recursive Functions Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own

More information

Lecture 6: Recursion RECURSION

Lecture 6: Recursion RECURSION Lecture 6: Recursion RECURSION You are now Java experts! 2 This was almost all the Java that we will teach you in this course Will see a few last things in the remainder of class Now will begin focusing

More information

CS 151. Recursion (Review!) Wednesday, September 19, 12

CS 151. Recursion (Review!) Wednesday, September 19, 12 CS 151 Recursion (Review!) 1 Announcements no class on Friday, and no office hours either (Alexa out of town) unfortunately, Alexa will also just be incommunicado, even via email, from Wednesday night

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion? CH. 5 RECURSION ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OVERVIEW Recursion is an algorithmic

More information

1.7 Recursion. Department of CSE

1.7 Recursion. Department of CSE 1.7 Recursion 1 Department of CSE Objectives To learn the concept and usage of Recursion in C Examples of Recursion in C 2 Department of CSE What is recursion? Sometimes, the best way to solve a problem

More information

March 13/2003 Jayakanth Srinivasan,

March 13/2003 Jayakanth Srinivasan, Statement Effort MergeSort(A, lower_bound, upper_bound) begin T(n) if (lower_bound < upper_bound) Θ(1) mid = (lower_bound + upper_bound)/ 2 Θ(1) MergeSort(A, lower_bound, mid) T(n/2) MergeSort(A, mid+1,

More information

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Recursion: The concept of recursion Recursive methods Infinite recursion When to use (and

More information

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5 What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion

More information

O(n): printing a list of n items to the screen, looking at each item once.

O(n): printing a list of n items to the screen, looking at each item once. UNIT IV Sorting: O notation efficiency of sorting bubble sort quick sort selection sort heap sort insertion sort shell sort merge sort radix sort. O NOTATION BIG OH (O) NOTATION Big oh : the function f(n)=o(g(n))

More information

SECTION 5.1. Sequences

SECTION 5.1. Sequences SECTION 5.1 Sequences Sequences Problem: count number of ancestors one has 2 parents, 4 grandparents, 8 greatgrandparents,, written in a row as 2, 4, 8, 16, 32, 64, 128, To look for pattern of the numbers,

More information

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function Functions in C++ Functions For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Declarations vs Definitions Inline Functions Class Member functions Overloaded

More information

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 CS 5301 Spring 2015 Jill Seaman 1 Definitions of Search and Sort! Search: find a given item in a list, return the position of the item, or -1 if not found.!

More information

Tutorial 3: Infix, Prefix, Postfix & Tower of Hanoi

Tutorial 3: Infix, Prefix, Postfix & Tower of Hanoi Tutorial 3: Infix, Prefix, Postfix & Tower of Hanoi ? 2 Consider the following operation performed on a stack of size 5. Push(1); Pop(); Push(2); Push(3); Pop(); Push(4); Pop(); Pop(); Push(5); a) 1 b)

More information

We cover recursion in 150. Why do it again in 151?

We cover recursion in 150. Why do it again in 151? Recursion We cover recursion in 150. Why do it again in 151? First, good solutions to problems are often recursive. Here is a quick way to sort a list of objects: split the list in half, recursively sort

More information

CS302 Data Structures using C++

CS302 Data Structures using C++ CS302 Data Structures using C++ Study Guide for the Final Exam Fall 2018 Revision 1.1 This document serves to help you prepare towards the final exam for the Fall 2018 semester. 1. What topics are to be

More information

Recursion. notes Chapter 8

Recursion. notes Chapter 8 Recursion notes Chapter 8 1 Tower of Hanoi A B C move the stack of n disks from A to C can move one disk at a time from the top of one stack onto another stack cannot move a larger disk onto a smaller

More information

- Wikipedia Commons. Intro Problem Solving in Computer Science 2011 McQuain

- Wikipedia Commons. Intro Problem Solving in Computer Science 2011 McQuain Recursion Recursion 1 Around the year 1900 the illustration of the "nurse" appeared on Droste's cocoa tins. This is most probably invented by the commercial artist Jan (Johannes) Musset, who had been inspired

More information