recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1



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

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

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

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

Analysis of Binary Search algorithm and Selection Sort algorithm

Computer Science 210: Data Structures. Searching

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

Lecture Notes on Linear Search

Binary search algorithm

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Section IV.1: Recursive Algorithms and Recursion Trees

Pseudo code Tutorial and Exercises Teacher s Version

Recursion and Dynamic Programming. Biostatistics 615/815 Lecture 5

Analysis of a Search Algorithm

Sample Questions Csci 1112 A. Bellaachia

Common Data Structures

6. Standard Algorithms

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

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

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

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

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

Recursion vs. Iteration Eliminating Recursion

Comp151. Definitions & Declarations

DATA STRUCTURES USING C

Module 2 Stacks and Queues: Abstract Data Types

6. Control Structures

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

GRID SEARCHING Novel way of Searching 2D Array

CSI33 Data Structures

Stacks. Linear data structures

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

B-Trees. Algorithms and data structures for external memory as opposed to the main memory B-Trees. B -trees

4.2 Sorting and Searching

CompSci-61B, Data Structures Final Exam

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

AP Computer Science Java Mr. Clausen Program 9A, 9B

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

Programming Languages

Loop Invariants and Binary Search

Linear Programming Notes V Problem Transformations

Solving Problems Recursively

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

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

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

Functional Programming in C++11

Searching Algorithms

PIC 10A. Lecture 7: Graphics II and intro to the if statement

csci 210: Data Structures Recursion

Binary Heap Algorithms

Shortest Path Algorithms

More MIPS: Recursion. Computer Science 104 Lecture 9

Chapter 7: Additional Topics

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

C++FA 5.1 PRACTICE MID-TERM EXAM

Binary Search Trees CMPSC 122

Data Structures. Algorithm Performance and Big O Analysis

COMPUTER SCIENCE 1999 (Delhi Board)

Data Structures and Data Manipulation

Introduction to data structures

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

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

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

CSC148 Lecture 8. Algorithm Analysis Binary Search Sorting

Lecture 12 Doubly Linked Lists (with Recursion)

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

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

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Recursion and Recursive Backtracking

Compiling Recursion to Reconfigurable Hardware using CLaSH

Data Structures and Algorithms V Otávio Braga

Chapter 5 Functions. Introducing Functions

Data Structures Using C++ 2E. Chapter 5 Linked Lists

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:

Zabin Visram Room CS115 CS126 Searching. Binary Search

Lecture 2 Notes: Flow of Control

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Sequential Data Structures

Ordered Lists and Binary Trees

10CS35: Data Structures Using C

Data Structures and Algorithms Written Examination

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

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

Previous Lectures. B-Trees. External storage. Two types of memory. B-trees. Main principles

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Data Structures and Algorithms

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

Introduction to Data Structures

APP INVENTOR. Test Review

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

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

Transcription:

topics: recursion searching cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1 recursion recursion is defining something in terms of itself there are many examples in nature and in mathematics and in computer graphics, e.g., the Koch snowflake cis15-fall2007-sklar-lecvi.1 1 cis15-fall2007-sklar-lecvi.1 2 power function here it is in C++ power is defined recursively: x y = if y == 0, x y = 1 if y == 1, x y = x otherwise, x y = x x y 1 // r1.cpp int power( int x, int y ) { if ( y == 0 ) return( 1 ); if ( y == 1 ) return( x ); return( x * power( x, y-1 )); // end of power() cout << "2^3 = " << power( 2,3 ) << endl; Notice that power() calls itself! cis15-fall2007-sklar-lecvi.1 3 cis15-fall2007-sklar-lecvi.1 4

You can do this with any method except main() BUT beware of infinite loops!!! You have to know when and how to stop the recursion what is the stopping condition call x y return value 1 power( 2,4 ) 2 4 2 * power( 2,3 ) 2 power( 2,3 ) 2 3 2 * power( 2,2 ) 3 power( 2,2 ) 2 2 2 * power( 2,1 ) 4 power( 2,1 ) 2 1 2 the first is the original call followed by three recursive calls let s walk through power( 2,4 ) cis15-fall2007-sklar-lecvi.1 5 cis15-fall2007-sklar-lecvi.1 6 stacks another example: factorial the computer uses a data structure called a stack to keep track of what is going on think of a stack like a stack of plates you can only take off the top one you can only add more plates to the top this corresponds to the two basic stack operations: push putting something onto the stack pop taking something off of the stack when each recursive call is made, power() is pushed onto the stack when each return is made, the corresponding power() is popped off of the stack factorial is defined recursively: if N == 1, N! = 1 N! = otherwise, N! = N (N 1)! (for N > 0) cis15-fall2007-sklar-lecvi.1 7 cis15-fall2007-sklar-lecvi.1 8

here it is in C++ recursive iteration // r2.cpp int factorial ( int N ) { if ( N == 1 ) return( 1 ); return( N * factorial( N-1 )); // end of factorial() cout << "5! = " << factorial( 5 ) << endl; You can also use recursion to iterate. Here s an example. Compare printi() (iterative) with printr() (recursive). // r3.cpp class array { private: int *data; int size; public: array( int n ) : size( n ) { data = new int[n]; void set( int x, int v ) { data[x] = v; void printi(); void printr( int x ); ; // end of class array cis15-fall2007-sklar-lecvi.1 9 cis15-fall2007-sklar-lecvi.1 10 void array::printi() { for ( int i=0; i<size; i++ ) cout << data[i] << " "; cout << endl; // end of printi() void array::printr( int x ) { if ( x < size ) { cout << data[x] << " "; printr( x+1 ); cout << endl; // end of printr() A.set( i,i*10 ); cout << "output from iterative printi(): "; A.printI(); cout << "output from recursive printr(): "; A.printR( 0 ); // end of main() method output from iterative printi(): 0 10 20 30 40 output from recursive printr(): 0 10 20 30 40 array A( 5 ); for ( int i=0; i<5; i++ ) cis15-fall2007-sklar-lecvi.1 11 cis15-fall2007-sklar-lecvi.1 12

and the details... in the recursive version, each call is like one iteration inside the for loop in the iterative version call index output next call 1 printr( 0 ) 0 0 printr( 1 ) 2 printr( 1 ) 1 10 printr( 2 ) 3 printr( 2 ) 2 20 printr( 3 ) 4 printr( 3 ) 3 30 printr( 4 ) 5 printr( 4 ) 4 40 printr( 5 ) 6 printr( 5 ) 5 endl (none) With recursion, each time the function is invoked, one step is taken towards the resolution of the task the function is meant to complete. Before each step is executed, the state of the task being completed is somewhere in the middle of being completed. After each step, the state of the task is one step closer to completion. In the example above, each time printr( i ) is called, the array is printed from the i-th element to the end of the array. In the power(x,y) example, each time the function is called, power is computed for each x y, in terms of the previous x y 1. In the factorial(n) example, each time the function is called, factorial is computed for each N, in terms of the previous N 1. cis15-fall2007-sklar-lecvi.1 13 cis15-fall2007-sklar-lecvi.1 14 searching linear search on UNSORTED DATA Often, when you have data stored in an array, you need to locate an element within that array. This is called searching. Typically, you search for a key value (simply the value you are looking for) and return its index (the location of the value in the array) As with sorting, there are many searching algorithms. We ll study the following: linear search standard linear search, on sorted or unsorted data modified linear search, on sorted data only binary search iterative binary search, on sorted data only recursive binary search, on sorted data only Linear search simply looks through all the elements in the array, one at a time, and stops when it finds the key value. This is inefficient, but if the array you are searching is not sorted, then it may be the only practical method. // s1.cpp class array { private: int *data; int size; public: array( int n ) : size( n ) { data = new int[n]; void set( int x, int v ) { data[x] = v; int getsize() { return size; cis15-fall2007-sklar-lecvi.1 15 cis15-fall2007-sklar-lecvi.1 16

int getitem( int x ) { return data[x]; void print( int x ); int linearsearch( int key ); ; // end of class array void array::print( int x ) { if ( x < size ) { cout << data[x] << " "; print( x+1 ); cout << endl; // end of array::print() int array::linearsearch( int key ) { for ( int i=0; i<getsize(); i++ ) { if ( key == getitem( i )) { return( i ); cis15-fall2007-sklar-lecvi.1 17 // end for i // end of array::linearsearch() int x; array A( 5 ); for ( int i=0; i<5; i++ ) A.set( i,i*10 ); cout << "here is the array: "; A.print( 0 ); cout << "looking for item 30..."; x = A.linearSearch( 30 ); if ( x == -1 ) cout << "\n"; cout << "found at location: " << x << endl; cout << "looking for item 65..."; x = A.linearSearch( 65 ); if ( x == -1 ) cis15-fall2007-sklar-lecvi.1 18 cout << "\n"; cout << "found at location: " << x << endl; // end of main() method here is the array: 0 10 20 30 40 looking for item 30... looking for item 65... linear search on SORTED data If the array you are searching IS SORTED, then you can modify the linear search to stop searching if you have looked past the place where the key would be stored if it were in the array. This only helps shorten the run time if the key is not in the array... Below is an example that works when the array is sorted in ascending order (from smallest to largest). Note that it also counts and prints out the number of times the for loop is called, so that you can compare the number of iterations for this version as opposed to the previous linearsearch() function. int array::linearsearchsorted( int key ) { int count = 0; for ( int i=0; i<getsize(); i++ ) { count++; if ( key == getitem( i )) { return( i ); cis15-fall2007-sklar-lecvi.1 19 cis15-fall2007-sklar-lecvi.1 20

if ( key < getitem( i )) { // end for i // end of array::linearsearchsorted() here is the array: 0 10 20 30 40 looking for item 30 using linearsearch()...count=4 looking for item 15 using linearsearch()...count=5 looking for item 30 using linearsearchsorted()...count=4 looking for item 15 using linearsearchsorted()...count=3 binary search Binary search is much more efficient than linear search, BUT ONLY WORKS ON A SORTED ARRAY. It CANNOT be used on an unsorted array! It takes the strategy of continually dividing the search space into two halves, hence the name binary. Say you are searching something very large, like the phone book. If you are looking for one name (e.g., Gilligan ), it is extremely slow and inefficient to start with the A s and look at each name one at a time, stopping only when you find Gilligan. This is what linear search does. Binary search acts much like you d act if you were looking up Gilligan in the phone book. You d open the book somewhere in the middle, then determine if Gilligan appears before or after the page you have opened to. If Gilligan appears after the page you ve selected, then you d open the book to a later page. cis15-fall2007-sklar-lecvi.1 21 cis15-fall2007-sklar-lecvi.1 22 If Gilligan appears before the page you ve selected, then you d open the book to an earlier page. You d repeat this process until you found the entry you are looking for. For example: int array::binarysearch( int key ) { int count = 0; int lo = 0, hi = getsize()-1, mid; while ( lo <= hi ) { count++; mid = ( lo + hi ) / 2; if ( key == getitem( mid )) { return( mid ); if ( key < getitem( mid )) { hi = mid - 1; lo = mid + 1; cis15-fall2007-sklar-lecvi.1 23 // end while // end of array::binarysearch() here is the array: 0 10 20 30 40 looking for item 30 using linearsearch()...count=4 looking for item 15 using linearsearch()...count=5 looking for item 30 using linearsearchsorted()...count=4 looking for item 15 using linearsearchsorted()...count=3 looking for item 30 using binarysearch()...count=2 looking for item 15 using binarysearch()...count=3 cis15-fall2007-sklar-lecvi.1 24

recursive binary search Binary search lends itself very well to a recursive implementation. Here s the previous binary search re-written as a recursive function: // end of array::recursivebinarysearch() int array::recursivebinarysearch( int key, int lo, int hi ) { if ( lo <= hi ) { int mid = ( lo + hi ) / 2; if ( key == getitem( mid )) { return( mid ); if ( key < getitem( mid )) { return( recursivebinarysearch( key, lo, mid-1 )); return( recursivebinarysearch( key, mid+1, hi )); cis15-fall2007-sklar-lecvi.1 25 cis15-fall2007-sklar-lecvi.1 26