The files IList.java, MTList.java, and ConsList.java that define a generic cons-list that implements the Traversal interface.

Similar documents
10 Generating Javadocs; HashMap: Overriding equals

7 Abstracting over the Data Type; Java Documentation; Direct Access Data Structures

26 How Many Times Must a White Dove Sail...

6 Starting in Eclipse

Types of recursion. Structural vs. general recursion. Pure structural recursion. Readings: none. In this module: learn to use accumulative recursion

Types of recursion. Readings: none. In this module: a glimpse of non-structural recursion. CS 135 Winter : Types of recursion 1

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

How to Design Programs

Sorting. Task Description. Selection Sort. Should we worry about speed?

Module 8: Local and functional abstraction

ormap, andmap, and filter

Searching & Sorting in Java Bubble Sort

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter --

Module 5: Lists. Readings: HtDP, Sections 9, 10.

Mutating Object State and Implementing Equality

21 Abstracting Traversals

Rewriting your function using map and foldr

CP222 Computer Science II. Searching and Sorting

Do you remember any iterative sorting methods? Can we produce a good sorting method by. We try to divide and conquer: break into subproblems

Assignment: 7. Due: Language level: Allowed recursion:

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Assignment 2. CS 234 Fall 2018 Sandy Graham. Create()

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction

Curriculum Map Grade(s): Subject: AP Computer Science

[1] Strings, Arrays, Pointers, and Hashing

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

Expression Values Operators. (string-append a b c ) a, b, c string-append. (substring abcd 0 2) abcd, 0, 2 substring

Unit 10: Sorting/Searching/Recursion

UE Algorithmen und Datenstrukturen 1 UE Praktische Informatik 1. Übung 9. Sorting

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Module 08: Searching and Sorting Algorithms

Component 02. Algorithms and programming. Sorting Algorithms and Searching Algorithms. Matthew Robinson

APCS Semester #1 Final Exam Practice Problems

Repetition Through Recursion

Bubble sort is so named because the numbers are said to bubble into their correct positions! Bubble Sort

CS 1101 Exam 3 A-Term 2013

! 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.

Lecture Notes on Linear Search

Lecture 4 Searching Arrays

Intro to Algorithms. Professor Kevin Gold

CSE 2123 Sorting. Jeremy Morris

Outline. Computer Science 331. Three Classical Algorithms. The Sorting Problem. Classical Sorting Algorithms. Mike Jacobson. Description Analysis

Advanced Sorting. Merge Sort Quick Sort Radix Sort

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Homework 8: Matrices Due: 11:59 PM, Oct 30, 2018

SORTING AND SEARCHING

ECE 242 Data Structures and Algorithms. Heaps I. Lecture 22. Prof. Eric Polizzi

CS115 - Module 9 - filter, map, and friends

Topics for CSCI 151 Final Exam Wednesday, May 10

L14 Quicksort and Performance Optimization

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Data structure is an organization of information, usually in memory, for better algorithm efficiency.

CSC 273 Data Structures

Chapter Contents. An Introduction to Sorting. Selection Sort. Selection Sort. Selection Sort. Iterative Selection Sort. Chapter 9

n 1 x i = xn 1 x 1. i= (2n 1) = n 2.

COMP2012H Spring 2014 Dekai Wu. Sorting. (more on sorting algorithms: mergesort, quicksort, heapsort)

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms;

Lecture 6 Sorting and Searching

ECE 2400 Computer Systems Programming, Fall 2017 Programming Assignment 3: Sorting Algorithms

CS 2510 Exam 3 SOLUTION Spring 2011

Analysis of Algorithms. Unit 4 - Analysis of well known Algorithms

Computer Science 1000: Part #2. Algorithms

CSCI 200 Lab 11 A Heap-Based Priority Queue

Answers to review questions from Chapter 2

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

Generative and accumulative recursion. What is generative recursion? Example revisited: GCD. Readings: Sections 25, 26, 27, 30, 31

C22a: Problem Solving using Recursion

Question 7.11 Show how heapsort processes the input:

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Chapter 10 - Notes Applications of Arrays

Functional Programming. Pure Functional Programming

Java SE 8 New Features

Tail Recursion: working from the beginning towards the end.

In addition to the correct answer, you MUST show all your work in order to receive full credit.

The results for a few specific cases below are indicated. allequal ([1,1,1,1]) should return true allequal ([1,1,2,1]) should return false

public static <E extends Comparable<? super E>>void BubbleSort(E[] array )

Introduction to Object-Oriented Programming

Points off Total off Net Score. CS 314 Final Exam Spring 2016

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011

Data Structures and Algorithms Notes

6.001 Notes: Section 4.1

CS 251 Intermediate Programming Methods and Classes

Binary Search Tree. Revised based on textbook author s notes.

CS 251 Intermediate Programming Methods and More

CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015

CP222 Computer Science II. Recurrence Relations and Basic Sorting

UNIT 7. SEARCH, SORT AND MERGE

Administrivia. HW on recursive lists due on Wednesday. Reading for Wednesday: Chapter 9 thru Quicksort (pp )

Lecture 17. Improving open-addressing hashing. Brent s method. Ordered hashing CSE 100, UCSD: LEC 17. Page 1 of 19

Lists. Readings: HtDP, sections 9 and 10. Avoid 10.3 (uses draw.ss). CS 135 Winter : Lists 1

Module 10: Imperative Programming, Modularization, and The Future

CS 1110: Introduction to Computing Using Python Loop Invariants

You must bring your ID to the exam.

CS212 - COMPUTATIONAL STRUCTURES AND ALGORITHMS

CSE 341 Section Handout #6 Cheat Sheet

CS 302: Introduction to Programming in Java. Lecture 12

1 Dynamic Programming

Comp Intermediate Programming EXAM #2 March 30, 2005 Rice University - Instructors: Cox & Nguyen

Transcription:

Lab 9 c 2010 Felleisen, Proulx, et. al. 9 Loops; Sorting Goals In the first part of the lab you will learn how to convert recursive loops to imperative (mutating) loops using either the Java while statement or the Java for statement to implement the imperative loops. In the second part we will look at how we can leverage the direct access to the items within the data set to implement a new kind of sorting algorithm. For this lab download the files in Lab9-fl2010.zip. The folder contains the following files: The file Balloon.java our sample data class The file ISelect.java the interface for a generic predicate method The files RedBallon and SmallBalloon that implement the ISelect interface for the Balloon data. The files IList.java, MTList.java, and ConsList.java that define a generic cons-list that implements the Traversal interface. The file ArrListTraversal.java shows how we can define a Traversal wrapper for the ArrayList class. The Algorithms.java file shows an implementation of several algorithms that consume data generated by a Traversal iterator and illustrates a number of ways in which loops can be implemented in Java. The Examples.java file that defines examples of all data and defines all tests. Create a new Project Lab9 and import into it all files from the zip file. Import the tester.jar and colors.jar. 9.1 Converting Recursive Loops into Imperative while Loops The goal of this part of the lab is to make sure you know how to implement a traversal over data within an ArrayList using Java while and for 1

c 2010 Felleisen, Proulx, et. al. Lab 9 loops. Make sure you understand the role of each part of the loop method definition: BASE VALUE, CONTINUATION-PREDICATE, CURRENT, AD- VANCE, UPDATE, and know how to construct both the while loop and the for loop. Work with the Lab handout. The first page gives you an overview of all classes and interfaces and the relationship between them. We introduce a dotted line from a method that consumes an instance of some class to that class. Read first the code for the contains method and for the countsuch method in the Algorithms class. These have been designed in the classical HtDP style. We will look together at the next two examples of ormap in the Algorithms class. We first write down the template for the case we already know the one where the loop uses the Traversal iterator. As we have done in class, we start by converting the recursive method into a form that uses the accumulator to keep track of the knowledge we already have, and passes that information to the next recursive invocation. Read carefully the Template Analysis and make sure you understand the meaning of all parts. 2

Lab 9 c 2010 Felleisen, Proulx, et. al. TEMPLATE - ANALYSIS: -------------------- return-type method-name(traversal tr){ +--------------------+ // invoke the methodacc: acc <-- BASE-VALUE +--------------------+ method-name-acc(traversal tr, BASE-VALUE); return-type method-name-acc(traversal tr, return-type acc)... tr.isempty()... -- boolean ::PREDICATE if true:... acc -- return-type ::BASE-VALUE if false: +---------------+... tr.getfirst()... -- E ::CURRENT +---------------+... update(t, return-type) -- return-type ::UPDATE i.e.:... update(tr.getfirst(), acc)...... tr.getrest() -- Traversal<T> ::ADVANCE... method-name(tr.getrest(), return-type) -- return-type i.e.:... method-name-acc(tr.getrest(), update(tr.getfirst(), acc)) Based on this analysis, we can now design a template for the entire problem with the solution divided into three methods as follows: COMPLETE METHOD TEMPLATE: ------------------------- <T> return-type method-name(traversal<t> tr){ +------------+ method-name-acc(traversal tr, BASE-VALUE ); +------------+ <T> return-type method-name(traversal<t> tr, return-type acc){ if ( tr.isempty() ) return acc; else return method-name-acc( tr.getrest(), update(tr.getfirst(), acc) ); <T> return-type update(t t, return-type acc){... 3

c 2010 Felleisen, Proulx, et. al. Lab 9 Understanding ormap Look at the first two variants of the ormap method (the recursively defined variant and the variant that uses the while loop. Identify the four parts (BASE-VALUE, Termination/Continuation PREDICATE, UPDATE, and ADVANCE) in each of them. Look also at the tests in the Examples class. After you understand how the while loop works, design two variants of the method that produces a new ArrayList that contains all elements of the original list that satisfy the given ISelect predicate. Test the methods by producing all red balloons or all small balloons. Design and test two variants of the andmap method that determines whether all elements of a given list satisfy the given ISelect predicate. Test the methods by checking whether a list contains all red balloons or all small balloons. Converting while loops into for loops Repeat all the parts of the previous task with the remaining two variants of the ormap namely the one that uses the for loop with the Traversal and the one that uses counted for loop. For Each Optionally, you may look at the ultimate abstraction of these traversals shown in the ForEach class. 1. Read the tests for for each variant of the compute method of the ForEach class shown in the Examples class. Make sure you understand how they work. Design additional tests for each of the three compute methods. 4

Lab 9 c 2010 Felleisen, Proulx, et. al. 9.2 Sorting Selection sort is one of the familiar sorting algorithms. It is well suited for the situations where you are trying to minimize the moving of the data from one location to another. Suppose you have an ArrayList of data of size s in which the first k elements are sorted, and every item in the unsorted part is greater than the largest item in the sorted part. You would like to sort the rest of the ArrayList. We know how to swap two items in the ArrayList. So, if we can find the location of the smallest item in the unsorted part and swap it with the first item in the unsorted part, the sorted part will be one item bigger, and the unsorted part will be one item smaller. If we repeat this until the last item is swapped into its correct position, we will have finished sorting the remainder of the ArrayList. Here is an example: >--- sorted ------< >--- unsorted ------------< +----+----+----+----++----+----+----+----+----+----+ 0 1 2 3 4 5 6 7 8 9 +----+----+----+----++----+----+----+----+----+----+ 13 16 17 20 27 31 22 25 28 29 +----+----+----+----++----+----+----+----+----+----+ Swap elements at locations 4 and 6: >-------- sorted ------< >--- unsorted -------< +----+----+----+----+----++----+----+----+----+----+ 0 1 2 3 4 5 6 7 8 9 +----+----+----+----+----++----+----+----+----+----+ 13 16 17 20 22 31 27 25 28 29 +----+----+----+----+----++----+----+----+----+----+ Swap elements at locations 5 and 7: >--------- sorted ----------< >--- unsorted ---< +----+----+----+----+----+----++----+----+----+----+ 0 1 2 3 4 5 6 7 8 9 +----+----+----+----+----+----++----+----+----+----+ 13 16 17 20 22 25 27 31 28 29 +----+----+----+----+----+----++----+----+----+----+ 5

c 2010 Felleisen, Proulx, et. al. Lab 9 Swap elements at locations 6 and 6: >----------- sorted -------------< >- unsorted -< +----+----+----+----+----+----+----++----+----+----+ 0 1 2 3 4 5 6 7 8 9 +----+----+----+----+----+----+----++----+----+----+ 13 16 17 20 22 25 27 31 28 29 +----+----+----+----+----+----+----++----+----+----+ What about the case when none of the ArrayList is sorted? Well, then the sorted part has size 0, and the unsorted part starts at the index 0. 1. In the Algorithms class design the helper method findminloc that finds the location of the smallest item in the unsorted part of the given ArrayList. Note: Think carefully through the first step of the design recipe, to make sure you know what the method consumes and what does it produce. 2. In the Algorithms class design the method selectionsort that implements the selection sort algorithm. 3. Design two Comparators for the Balloons, the BalloonsBySize that compares the balloons by their radius, and BalloonsByHeight that compares them by their distance to the top. 4. Test your sorting method and the helper method on lists of balloons using each of the two Comparators. 6