Programming II (CS300)

Similar documents
Programming II (CS300)

Programming II (CS300)

Programming II (CS300)

RECURSION. Data Structures & SWU Rachel Cardell- Oliver

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Analyzing Complexity of Lists

Recursion. Chapter 11. Chapter 11 1

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

Fun facts about recursion

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

C22a: Problem Solving using Recursion

Announcement. Submit assignment 3 on CourSys Do not hand in hard copy Due Friday, 15:20:00. Caution: Assignment 4 will be due next Wednesday

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Lecture 6 Sorting and Searching

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

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

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Data structure and algorithm in Python

Plan of the lecture. Quick-Sort. Partition of lists (or using extra workspace) Quick-Sort ( 10.2) Quick-Sort Tree. Partitioning arrays

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

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms

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

Recursion. Chapter 11

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

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

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

UNIT-2. Problem of size n. Sub-problem 1 size n/2. Sub-problem 2 size n/2. Solution to the original problem

CS302 - Data Structures using C++

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Recursive Definitions

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CSC 1052 Algorithms & Data Structures II: Recursion

CSE 230 Computer Science II (Data Structure) Introduction

LECTURE 08 SEARCHING AND SORTING ARRAYS

Chapter 15: Recursion

Programming II (CS300)

Programming Abstractions

Complexity of Algorithms

Lecture Notes on Quicksort

Reduction & Recursion Overview

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Cosc 241 Programming and Problem Solving Lecture 7 (19/3/18) Arrays

Module 10. Recursion. Adapted from Absolute Java, Rose Williams, Binghamton University

PDF created with pdffactory Pro trial version Recursion

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Recursion Chapter 3.5

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

Fundamental mathematical techniques reviewed: Mathematical induction Recursion. Typically taught in courses such as Calculus and Discrete Mathematics.

Lecture Notes on Quicksort

COS 226 Algorithms and Data Structures Fall Midterm Solutions

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

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

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

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

Lecture 7 Quicksort : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Searching in General

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

CS 351 Design of Large Programs Programming Abstractions

Sorting L7.2 Recall linear search for an element in an array, which is O(n). The divide-and-conquer technique of binary search divides the array in ha

Programming II (CS300)

Programming II (CS300)

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

Chapter 8 Search and Sort

6/4/12. Recursive void Methods. Chapter 11. Vertical Numbers. Vertical Numbers. Vertical Numbers. Algorithm for Vertical Numbers

Recursion. Chapter 5

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

CS103L SPRING 2017 UNIT 8: RECURSION

1 Dynamic Memory continued: Memory Leaks

Active Learning: Sorting

Divide-and-Conquer. Divide-and conquer is a general algorithm design paradigm:

Topic 14 Searching and Simple Sorts

CSE 214 Computer Science II Recursion

ECE 122. Engineering Problem Solving Using Java

CSc 110, Spring 2017 Lecture 39: searching

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

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

BM267 - Introduction to Data Structures

CS:3330 (22c:31) Algorithms

A function that invokes itself is said to

CSE 230 Intermediate Programming in C and C++ Recursion

COMP Data Structures

Largest Online Community of VU Students

SORTING. Comparison of Quadratic Sorts

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Language Proposal: tail

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Programming II (CS300)

Unit 10: Sorting/Searching/Recursion

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

NCS 301 DATA STRUCTURE USING C

CS102 Sorting - Part 2

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

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

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

Transcription:

1 Programming II (CS300) Chapter 10 Recursion and Search MOUNA KACEM

Recursion: General Overview 2 Recursion in Algorithms Recursion is the use of recursive algorithms to solve a problem A recursive algorithm uses itself to solve one or more smaller identical problems Recursion in Java A recursive method implements a recursive algorithm A recursive method is a method that directly or indirectly makes a call to itself

Recursion: General Overview The recursion can be direct : the method calls itself indirect : the method calls another method that calls the first method single : the method calls itself once Multiple : the method calls itself multiple times Direct Recursion public void f(){ f() public void f(){ f() public void f(){ f() Indirect Recursion public void f( ){ g( ) public void g( ){ f( ) public void f( ){ g( ) Multiple Recursion public void f(){ f() f() public void f(){ public void f(){ f() f() f() f() public void f(){ public void f(){ f() public f() void f(){ f() public f() void f(){ f() f() f() f() 3

Recursion: General Overview 4 public void f(input){ f(smaller_input) public void f(input){ f(smaller_input) public void f(input){ f(smaller_input) Recursion does not refer to a circular logic A recursive algorithm calls itself on a different, generally simpler, instance (i.e. with a smaller input)

Recursion: General Overview public output f(input){ f(smaller_input) public output f(input){ f(smaller_input) public output f(input){ f(smaller_input) public output f(input){ f(smaller_input) public output f(input){ f(smaller_input) public output f(input){ if base_case return else f(smaller_input) 5 The recursion calls should STOP to prevent infinite recursive regression! The recursive method must define a base case that stops the recursive call

Recursion: General Overview 6 Recursion Method Design Rules Recursive methods must terminate A recursive method must have at least one base case A base case does not execute a recursive call. It stops the recursion Recursive methods should include One or more base cases: refer to fixed values of the method One or more recursive cases: definition of the function in terms of itself Each recursive case must be a smaller version of itself Each recursive case must make progress toward the base case (i.e. the base case should be reached)

7 Basic Illustrative Example Factorial Function

Illustrative Example 1 - Factorial Function 8 Factorial Function: Formal Definition for any integer n 0, Example! 1 0 1 2 3 2 1 1 5! = 5 x 4 x 3 x 2 x 1 = 120 = 5 x (4 x 3 x 2 x 1) = 5 x 4! Recursive Definition The factorial function has a natural recursive definition for any integer n 0,! 1 0 1! 1

Illustrative Example 1: Factorial Function Recursive Definition for any integer n 0, 9 1 0! 1! 1 Recursive implementation of Factorial Public static int factorial(int n){ if (n == 0) return 1; // base case return n * factorial(n-1); // recursive case public static int recursivefactorial(int n) throws IllegalArgumentException{ if (n < 0) throw new IllegalArgumentException(); // argument must be positive else return factorial(n);

Illustrative Example 1: Factorial Function Recursive implementation of Factorial Public static int factorial(int n){ if (n == 0) return 1; // base case return n * factorial(n-1); // recursive case Each time the method executes it reduces the current problem to a smaller instance of the same problem calls itself to solve the smaller problem The recursion stops when the base case is reached Recursion Trace for n = 4 10 4! = 24 return 4 * 6 = 24 factorial(4)? = 4 * factorial(3) return 3 * 2 = 6 factorial(3)? = 3 * factorial(2) return 2 * 1 = 2 factorial(2)? = 2 * factorial(1) return 1 * 1 = 1 factorial(1)? = 1 * factorial(0) return 1 factorial(0) 1 = Factorial(0)

Illustrative Example 1: Factorial Function Recursive implementation of Factorial Iterative implementation of Factorial 11 Public static int factorial(int n){ if (n == 0) return 1; // base case return n * factorial(n-1); // recursive case Clearer (easier to understand) Running time: O(n) public static int interativefactorial(int n) throws IllegalArgumentException{ if (n < 0) throw new IllegalArgumentException(); // argument must be positive else if (n == 0) return 1; else{ int fact = n; for(int i=n-1; i>1; i--) fact = fact * i; return fact; Running time: O(n)

Illustrative Example 1: Factorial Function 12 How does the computer implements a program? A computer allocates two areas of memory for a program the stack to store information about method calls When a piece of code calls a method, information about the call is placed on the stack. When the method returns, that information is popped off the stack the heap to create variables and perform calculations The stack s space size is much smaller than the heap s one

Illustrative Example 1: Factorial Function 13 Java uses a stack called run-time stack to keep track of the function calls Call Stack Recursive Factorial Call Stack Iterative Factorial Each time a function is called recursively, an activation record is created and stored in the stack factorial(1) factorial(2) When recursion returns, the corresponding activation is popped off the stack factorial(3) factorial(4) Iteration simply ' jumps back' to the beginning of the loop recursivefactorial(4) factorial(4) A function call is usually more expensive than a jump console.log() main() console.log() main()

Important Rule 14 Do not use recursion as a substitute for a simple loop Recursion could be very slow because of the extra memory and time overhead due to function/method calls!

Designing Recursive Algorithms 15

Recursive Thinking 16 Problem SP 1 Is the problem simple enough to solve it directly? SP 2 SP N????? Decompose: break the problem into one or more smaller subproblems SP 1, SP 2,..., SP N

Recursive Thinking 17 Problem SP 1 SP 2 SP N Decompose the problem into one or more smaller sub-problems Is the (sub-)problem simple enough to solve it directly? Solve each subproblem recursively : solve(sp N ), solve(sp N-1 ),..., solve(sp 2 ) solve(sp 1 ) Combine results into a solution that solves the original Problem

Recursive Thinking 18 General Approach: if the problem is simple enough solve it directly else decompose into one or more smaller subproblems solve each subproblem recursively combine results into a solution to solve the original problem

General Recursive Design Strategy 19 1. Identify the base case(s) (for direct solution) 2. Decompose: define subproblems that have the same general structure as the original problem Subproblems must be smaller Subproblems must work towards a base case 3. Combine solutions from calls to other methods to obtain a solution for the original problem

Recursion - Keep in Mind 20 A recursive method is a method that invokes itself as a subroutine with a smaller input, until a base case is reached Base case not reached infinite recursive regression StackOverflowError Recursive programs not only simplify the algorithm design but also tend to give a cleaner code Recursion is a powerful programming tool that in many cases (not all cases) can yield both short and efficient algorithms

Recursion - Keep in Mind 21 Recursion is not always the best solution recursion might cause poor performance Sometimes algorithms that are naturally expressed recursively must be rewritten without recursion The main problem with recursion is the hidden bookkeeping costs Avoid using recursion in performance situations Recursive calls take time and consume additional memory

Search 22

Linear Search 23 Search: Problem Statement Given a target value X, return the index of X in the array, if such X exists. Otherwise, return (-1). Sequential Search or linear search is a search technique used to find a target value (or key value) within a list (here an array). It checks each element of the array for the target value from the first position to the last position in a linear progression (i.e. until a match is found (successful search) or until all the elements have been searched (unsuccessful search)).

Linear Search 24

Linear Search 25

Binary Search 26 Problem Description Locate a target value within a sequence of n elements sorted in an array Input: array A of n integer numbers sorted in ascending order Target: the search target element Output: index of the specified target in the given array of present, -1 otherwise A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84 indices values

Binary Search 27 Linear Search (or Sequential Search) for unsorted sequence Search Approach Use a loop to examine every element until either finding the target or exhausting the data set Running time : O(n) Binary Search Precondition: sorted and indexable sequence of numbers Target: 40 Arbitrary element e = 11 < 40 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84 The Target should be in this portion of the array if present Binary Search: compare the target value to the median

Binary Search 28 Binary Search Precondition: sorted and indexable sequence of numbers The algorithm maintains two parameters : low and high Initially, low = 0 and high = n-1 Binary Search Design Strategy: median high 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84 Compare the target value to the median one, that is the element with index mid = (low + high)/2 1. If the target equals the median value, then return mid and the search terminates successfully Base case 2. If the target is less than the median value, then recur on the left half of the sequence; (i.e. on the interval of indices [low, mid-1]) 3. If the target is greater than the median value, then recur on the right half of the sequence; (i.e. the interval of indices [mid +1, high]) 4. If low > high (i.e. the interval [low, high] is empty), then return -1 and the search terminates unsuccessfully Base case

Binary Search 29 // Precondition: elements of the array a are in sorted order public static int binarysearch(int[] a, int target) { return binarysearch(a, target, 0, a.length - 1); private static int binarysearch(int[] a, int target, int low, int high) { if (low > high) { return -1; // target not found (base case) else { int mid = (low + high) / 2; if (a[mid] < target) { // too small; go right return binarysearch(a, target, mid + 1, high); else if (a[mid] > target) { // too large; go left return binarysearch(a, target, low, mid - 1); else { return mid; // target found (base case)

Binary Search 30 Binary Search Precondition: sorted and indexable sequence of numbers Target: 40 If present, A[low] Target A[high] mid = (high + low)/2 low A[mid] = 33 < 40 high A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84 Initially, low = 0 and high = n-1 = 14

Binary Search 31 Binary Search Precondition: sorted and indexable sequence of numbers low mid A[mid] = 33 < 40 high Target: 40 A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84 low mid high 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 A[mid]= 51 > 40-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84 low mid high 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 A[mid]= 40 = Target return 9-2 3 5 10 11 18 21 33 35 40 42 51 67 69 84

Binary Search Keep in Mind 32 Precondition: Sorted array If the values in the array are arranged in ascending or descending order, then we call the array sorted. Assumption: The array is sorted in an ascendant order Basic idea: The search is performed by examining the median of a sorted array (the middle element) If match, target element found. Otherwise, if target element is smaller than the median, search in the subarray that is to the left of the median. Otherwise, search in the subarray that is to the right of the median. This procedure presumes that the subarray is not empty; if it is, the target element is not found.

Binary Search - Example 33 Search for 77 in the array arr Execution Trace (trace of visited nodes): 38, 77 Running Time: O(log(N)) An introduction to Oriented Programming with Java, C. Thomas Wu, Fifth edition, McGraw-Hill Companies Higher Education edition, 2010