Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Building Java Programs Chapter 13
Garfield AP Computer Science
CSE 373: Data Structures and Algorithms Lecture 5: Math Review/Asymptotic Analysis III 1.
Searching Chapter Chapter Contents The Problem Searching an Unsorted Array Iterative Sequential Search Recursive Sequential Search Efficiency of.
CSE 143 Lecture 5 Binary search; complexity reading: slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 11 Recursive Programming reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 12 Lecture 12-2: recursive programming reading:
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Building Java Programs Chapter 13 Searching reading: 13.3.
Recursion Chapter 11. The Basics of Recursion: Outline Introduction to Recursion How Recursion Works Recursion versus Iteration Recursive Methods That.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
CSE 143 Lecture 15 Binary Search; Comparable reading: 13.2; 10.2 slides created by Marty Stepp
CSE 143 Lecture 13 Recursive Programming reading: slides created by Marty Stepp
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Data Structure Introduction.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
CSE 143 Lecture 14 Maps/Sets; Grammars reading: slides adapted from Marty Stepp and Hélène Martin
Binary search and complexity reading:
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
Building Java Programs Chapter 13 Searching and Sorting Copyright (c) Pearson All rights reserved.
Building Java Programs Chapter 13 Lecture 13-1: binary search and complexity reading:
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Lecture 25: Searching and Sorting
Sort & Search Algorithms
CSc 110, Autumn 2016 Lecture 36: searching.
Lecture 10: recursive programming reading:
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs
Building Java Programs
CSE 143 Lecture 14 Searching and Comparable reading: ; 10.2
Building Java Programs
Lecture 14: binary search and complexity reading:
CSE 143 Lecture 5 Binary search; complexity reading:
CSc 110, Spring 2017 Lecture 39: searching.
Building Java Programs
Building Java Programs
CSE 143 Lecture 5 More Stacks and Queues; Complexity (Big-Oh)
slides adapted from Marty Stepp
Lecture 10: recursive programming reading:
CSE 143 Lecture 14 (A) More Recursive Programming
CSE 143 Lecture 11 Recursive Programming reading:
Lecture 15: binary search reading:
Building Java Programs
CSE 143 Lecture 14 More Recursive Programming; Grammars
CSE 143 Lecture 11 Recursive Programming slides created by Marty Stepp
CSE 373 Data Structures and Algorithms
CSE 143 Lecture 16 (A) Searching and Comparable
Building Java Programs
Building Java Programs
Recursion Based on slides by Alyssa Harding
Adapted from slides by Marty Stepp and Stuart Reges
slides created by Alyssa Harding
CSE 373 Data Structures and Algorithms
Building Java Programs
CSE 143 Lecture 13 Recursive Programming reading:
Building Java Programs
Building Java Programs
Sum this up for me Let’s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
Lecture 4: Introduction to Code Analysis
Building Java Programs
Lecture 10: recursive programming reading:
CSE 143 Lecture 14 Searching and Comparable reading: ; 10.2
slides created by Alyssa Harding
Searching.
Sorting Algorithms.
Presentation transcript:

Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3

2

3

4 Recursion and cases Every recursive algorithm involves at least 2 cases: base case: simple problem that can be solved directly. recursive case: more complex occurrence of the problem that cannot be directly answered, but can instead be described in terms of smaller occurrences of the same problem. Some recursive algorithms have more than one base or recursive case, but all have at least one of each. A crucial part of recursive programming is identifying these cases.

5 Recursion Challenges Forgetting a base case Infinite recursion resulting in StackOverflowError Working away from the base case The recursive case must make progress towards the base case Infinite recursion resulting in StackOverflowError Running out of memory Even when making progress to the base case, some inputs may require too many recursive calls: StackOverflowError Recomputing the same subproblem over and over again Refining the algorithm could save significant time

6 Exercise Write a method crawl accepts a File parameter and prints information about that file. If the File object represents a normal file, just print its name. If the File object represents a directory, print its name and information about every file/directory inside it, indented. cse143 handouts syllabus.doc lecture_schedule.xls homework 1-tiles TileMain.java TileManager.java index.html style.css recursive data: A directory can contain other directories.

7 File objects A File object (from the java.io package) represents a file or directory on the disk. Constructor/methodDescription File( String ) creates File object representing file with given name canRead() returns whether file is able to be read delete() removes file from disk exists() whether this file exists on disk getName() returns file's name isDirectory() returns whether this object represents a directory length() returns number of bytes in file listFiles() returns a File[] representing files in this directory renameTo( File ) changes name of file

8 Public/private pairs We cannot vary the indentation without an extra parameter: public static void crawl(File f, String indent) { Often the parameters we need for our recursion do not match those the client will want to pass. In these cases, we instead write a pair of methods: 1) a public, non-recursive one with parameters the client wants 2) a private, recursive one with the parameters we really need

9 Exercise solution 2 // Prints information about this file, // and (if it is a directory) any files inside it. public static void crawl(File f) { crawl(f, ""); // call private recursive helper } // Recursive helper to implement crawl/indent behavior. private static void crawl(File f, String indent) { System.out.println(indent + f.getName()); if (f.isDirectory()) { // recursive case; print contained files/dirs for (File subFile : f.listFiles()) { crawl(subFile, indent + " "); }

10 Recursive Data A file is one of A simple file A directory containing files Directories can be nested to an arbitrary depth Iterative code to crawl a directory structure requires data structures In recursive solution, we use the call stack

11 Binary search (13.1) binary search: Locates a target value in a sorted array/list by successively eliminating half of the array from consideration. Can be implemented with a loop or recursively Example: Searching the array below for the value 42: index value minmidmax

12 Binary search code // Returns the index of an occurrence of target in a, // or a negative number if the target is not found. // Precondition: elements of a are in sorted order public static int binarySearch(int[] a, int target) { int min = 0; int max = a.length - 1; while (min <= max) { int mid = (min + max) / 2; if (a[mid] < target) { min = mid + 1; } else if (a[mid] > target) { max = mid - 1; } else { return mid; // target found } return -(min + 1); // target not found }

13 Recursive binary search (13.3) Write a recursive binarySearch method. If the target value is not found, return its negative insertion point. int index = binarySearch(data, 42); // 10 int index2 = binarySearch(data, 66); // -14 index value

14 Ordering and objects Can we compare Strings? Operators like do not work with String objects. But we do think of strings as having an alphabetical ordering. natural ordering: Rules governing the relative placement of all values of a given type. comparison function: Code that, when given two values A and B of a given type, decides their relative ordering: A B

15 The compareTo method (10.2) The standard way for a Java class to define a comparison function for its objects is to define a compareTo method. Example: in the String class, there is a method: public int compareTo(String other) A call of A.compareTo( B ) will return: a value <0if A comes "before" B in the ordering, a value >0if A comes "after" B in the ordering, or0if A and B are considered "equal" in the ordering.

16 Using compareTo compareTo can be used as a test in an if statement. String a = "alice"; String b = "bob"; if (a.compareTo(b) < 0) { // true... } PrimitivesObjects if (a < b) {...if (a.compareTo(b) < 0) {... if (a <= b) {...if (a.compareTo(b) <= 0) {... if (a == b) {...if (a.compareTo(b) == 0) {... if (a != b) {...if (a.compareTo(b) != 0) {... if (a >= b) {...if (a.compareTo(b) >= 0) {... if (a > b) {...if (a.compareTo(b) > 0) {...

17 Exercise solution // Returns the index of an occurrence of the given value in // the given array, or a negative number if not found. // Precondition: elements of a are in sorted order public static int binarySearch(int[] a, int target) { return binarySearch(a, target, 0, a.length - 1); } // Recursive helper to implement search behavior. private static int binarySearch(int[] a, int target, int min, int max) { if (min > max) { return -1; // target not found } else { int mid = (min + max) / 2; if (a[mid] < target) { // too small; go right return binarySearch(a, target, mid + 1, max); } else if (a[mid] > target) { // too large; go left return binarySearch(a, target, min, mid - 1); } else { return mid; // target found; a[mid] == target }

18 Binary search runtime For an array of size N, it eliminates ½ until 1 element remains. N, N/2, N/4, N/8,..., 4, 2, 1 How many divisions does it take? Think of it from the other direction: How many times do I have to multiply by 2 to reach N? 1, 2, 4, 8,..., N/4, N/2, N Call this number of multiplications "x". 2 x = N x= log 2 N Binary search is in the logarithmic complexity class.

19 Complexity classes - post about a Google interview

20 See section 12.4 Recursive Graphics