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



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

Sample Questions Csci 1112 A. Bellaachia

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

Chapter 5. Recursion. Data Structures and Algorithms in Java

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

Introduction. Earlier programs structured as methods that call one another in a disciplined, hierarchical manner Recursive methods

10CS35: Data Structures Using C

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

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

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

Analysis of a Search Algorithm

Data Structure with C

Section IV.1: Recursive Algorithms and Recursion Trees

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:

Stack Allocation. Run-Time Data Structures. Static Structures

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

PES Institute of Technology-BSC QUESTION BANK

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

Sequential Data Structures

CompSci-61B, Data Structures Final Exam

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

CmpSci 187: Programming with Data Structures Spring 2015

csci 210: Data Structures Recursion

Common Data Structures

Efficiency of algorithms. Algorithms. Efficiency of algorithms. Binary search and linear search. Best, worst and average case.

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

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

Loop Invariants and Binary Search

Stacks. Linear data structures

(IALC, Chapters 8 and 9) Introduction to Turing s life, Turing machines, universal machines, unsolvable problems.

Lecture 12 Doubly Linked Lists (with Recursion)

Algorithms and Data Structures Written Exam Proposed SOLUTION

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

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

CS 103X: Discrete Structures Homework Assignment 3 Solutions

Data Structures and Algorithms Written Examination

J a v a Quiz (Unit 3, Test 0 Practice)

7.1 Our Current Model

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Binary search algorithm

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

Data Structures In Java

Pseudo code Tutorial and Exercises Teacher s Version

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

Data Structures. Level 6 C Module Descriptor

Lecture Notes on Linear Search

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Chapter 14 The Binary Search Tree

6. Standard Algorithms

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

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

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

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

Algorithms and Data Structures

Solving Problems Recursively

Algorithms are the threads that tie together most of the subfields of computer science.

St S a t ck a ck nd Qu Q eue 1

Unit 6. Loop statements

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

The ADT Binary Search Tree

Recursion and Recursive Backtracking

Optimal Binary Search Trees Meet Object Oriented Programming

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

4.2 Sorting and Searching

Moving from CS 61A Scheme to CS 61B Java

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:

Introduction to Programming System Design. CSCI 455x (4 Units)

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

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:

Binary Heap Algorithms

Lecture Notes on Binary Search Trees

DATA STRUCTURES USING C

Sources: On the Web: Slides will be available on:

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

STACKS,QUEUES, AND LINKED LISTS

Generating Elementary Combinatorial Objects

Introduction to data structures

Introduction to Stacks

Converting a Number from Decimal to Binary

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Module 2 Stacks and Queues: Abstract Data Types

Algorithms and Data Structures Exercise for the Final Exam (17 June 2014) Stack, Queue, Lists, Trees, Heap

Java Program Coding Standards Programming for Information Technology

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

3.5 RECURSIVE ALGORITHMS

Programming Exercises

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Algorithm Design and Recursion

Abstraction and Abstract Data Types

Searching Algorithms

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

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Keil C51 Cross Compiler

Computer Science 210: Data Structures. Searching

LINEAR INEQUALITIES. less than, < 2x + 5 x 3 less than or equal to, greater than, > 3x 2 x 6 greater than or equal to,

Symbol Tables. Introduction

Transcription:

Recursion Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive. Why recursion? o For many problems, the recursion solution is more natural than the alternative non-recursive or iterative solution o It is often relatively easy to prove the correction of recursive algorithms (often prove by induction). o Easy to analyze the performance of recursive algorithms. The analysis produces recurrence relation, many of which can be easily solved. Format of a recursive algorithm: o Algorithm name(parameters) Declarations; Begin if trivial case) then do trivial operations end; else begin end; - one or more call name(smaller values of parameters) - do few more operations: process the sub-solution(s). CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 1

Taxonomy: o Direct Recursion: It is when a function refers to itself directly o Indirect Recursion: It is when a function calls another function which refer to it. o Linear Recursion: It is when one a function calls itself only once. o Binary Recursion: A binary-recursive routine (potentially) calls itself twice. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 2

Examples o Printing a stack: Recursive method to print the content of a stack Printing the stack Z C Z C B A B A public void printstackrecursive() { if (isempty()) System.out.println("Empty Stack"); else{ System.out.println(top()); pop(); if (!isempty()) printstackrecursive(); } } o Palindrome: int function Palindrome(string X) Begin If Equal(S,StringReverse(S)) then return TRUE; else return False; end; CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 3

o Reversing a String: Pseudo-Code: string function StringReverse(string S) /* Head(S): returns the first character of S */ /* Tail(S): returns S without the first character */ begin If (Length(S) <=1) then return S; else return (concat(stringreverse(tail(s)) & Head(S)); endif; end; Java Code: public static String reverse1(string s) { //BASIS CASE if (s.length() == 0) return s; //RECURSIVE STEP (notice use of empty String to do conversion of characters) return ("" + s.charat(s.length() - 1) + reverse1(s.substring(0, s.length() - 1))); } CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 4

Performance o Definition: A recurrence relation of a sequence of values is defined as follows: (B) Some finite set of values, usually the first one or first few, are specified. (R) The remaining values of the sequence are defined in terms of previous values of the sequence. o Example: The familiar sequence of factorial is defined as: - (B) FACT(0) = 1 - (R) FACT(n+1) = (n+1)*fact(n) o Time Complexity: The analysis of a recursive algorithm is done using recurrence relation of the algorithm. Example 1: - The time complexity of StringReverse function: o Let T(n) be the time complexity of the function where n is the length of the string. o The recurrence relation is: (B) n=1 let T(n)=1 (R) n>1 let T(n)=T(n-1)+1 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 5

- Solution: T(n) = T(n-1)+1 T(n-1) = T(n-2)+1 T(n-2) = T(n-3)+1... T(3) = T(2)+1 T(2) = T(1)+1 T(n) = T(1)+1+1+1+...+1 = T(1)+(n-1) = n ===> T(n) = O(n Example 2: T ( n) = 2T ( n ) + C 2 C if if n> 1 n= 1 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 6

Assume that n = 2 k T(n) = 2T(n/2)+C 2T(n/2) = 2 2 T(n/4)+2C 2 2 T(n/4) = 2 3 T(n/8)+ 2 2 C... 2 k-2 T(n/2 k-2 ) = 2 k-1 T(n/2 k-1 )+ 2 k-2 C 2 k-1 T(n/2 k-1 ) = 2 k T(n/2 k )+ 2 k-1 C T(n) = 2 k T(1)+C+2C+2 2 C +...+2 k-2 C+2 k-1 C = T(n) = 2 k C +C(1+2+2 2 +...+2 k-2 +2 k-1 ) T(n) = nc +C T(n) = nc +C T(n) = nc +C 2 k 1 T(n) = nc +C 2 k T(n) = nc +nc=2nc ==> T(n) =O(n) k 1 2 k i 2 ( 1) + 1 1 2k = = 2k i 0 2 1 1 = = 2 ( k 1) + 1 1 2 1 CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 7

o Space Complexity: Each recursive call requires the creation of an activation record Each activation record contains the following: - Parameters of the algorithm (PAR) - Local variable (LC) - Return address (R @) - Stack link (SL) Example: SL R @ PAR LV SL R @ PAR LV SL R @ PAR LV Main Program: Local Variable CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 8

- Complexity: o Let P: parameters L: local variables 2: SL and R @ n: is the maximum recursive depth space= n*(p+l+2) Disadvantages: o Recursive algorithms require more time: At each call we have to save the activation record of the current call and Branch to the code of the called procedure At the exit we have the recover the activation record and return to the calling procedure. If the depth of recursion is large the required space may be significant. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 9

Lab Assignments: o What is the time complexity of the following function: T(n) = T(n 2 ) n > 1 C n = 1 o What is the time complexity of the following function: T(n) = T n 2 + n n > 1 C n = 1 o Write a recursive function that returns the total number of nodes in a singly linked list. CSci 1112 Algorithms and Data Structures, A. Bellaachia Page 10