Chapter 11 Array-Based Lists.

Slides:



Advertisements
Similar presentations
Numbers Treasure Hunt Following each question, click on the answer. If correct, the next page will load with a graphic first – these can be used to check.
Advertisements

EcoTherm Plus WGB-K 20 E 4,5 – 20 kW.
1 A B C
Simplifications of Context-Free Grammars
TK1924 Program Design & Problem Solving Session 2011/2012
AP STUDY SESSION 2.
1
Copyright © 2013 Elsevier Inc. All rights reserved.
David Burdett May 11, 2004 Package Binding for WS CDL.
Create an Application Title 1Y - Youth Chapter 5.
Process a Customer Chapter 2. Process a Customer 2-2 Objectives Understand what defines a Customer Learn how to check for an existing Customer Learn how.
Add Governors Discretionary (1G) Grants Chapter 6.
CALENDAR.
The 5S numbers game..
Media-Monitoring Final Report April - May 2010 News.
Break Time Remaining 10:00.
The basics for simulations
Factoring Quadratics — ax² + bx + c Topic
EE, NCKU Tien-Hao Chang (Darby Chang)
Turing Machines.
PP Test Review Sections 6-1 to 6-6
Topic 12 The List ADT. 9-2 Objectives Examine list processing and various ordering techniques Define a list abstract data type Examine various list implementations.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Chapter 10: Applications of Arrays and the class vector
1 IMDS Tutorial Integrated Microarray Database System.
Alan YorinksLecture 7 1 • Tonight we will look at:: • List ADT • Unsorted List • Sequential Search • Selection Sort • Sorted List • Binary Search.
ADTs unsorted List and Sorted List
Multicore Programming Skip list Tutorial 10 CS Spring 2010.
Double-Linked Lists and Circular Lists
Data structure is concerned with the various ways that data files can be organized and assembled. The structures of data files will strongly influence.
Briana B. Morrison Adapted from William Collins
2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions.
Regression with Panel Data
Operating Systems Operating Systems - Winter 2010 Chapter 3 – Input/Output Vrije Universiteit Amsterdam.
Numerical Analysis 1 EE, NCKU Tien-Hao Chang (Darby Chang)
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Biology 2 Plant Kingdom Identification Test Review.
Chapter 1: Expressions, Equations, & Inequalities
Lilian Blot PART III: ITERATIONS Core Elements Autumn 2012 TPOP 1.
Adding Up In Chunks.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
MaK_Full ahead loaded 1 Alarm Page Directory (F11)
1 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt 10 pt 15 pt 20 pt 25 pt 5 pt Synthetic.
1 Termination and shape-shifting heaps Byron Cook Microsoft Research, Cambridge Joint work with Josh Berdine, Dino Distefano, and.
Artificial Intelligence
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
Before Between After.
Slide R - 1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Prentice Hall Active Learning Lecture Slides For use with Classroom Response.
Subtraction: Adding UP
: 3 00.
5 minutes.
1 Non Deterministic Automata. 2 Alphabet = Nondeterministic Finite Accepter (NFA)
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
1 Let’s Recapitulate. 2 Regular Languages DFAs NFAs Regular Expressions Regular Grammars.
Types of selection structures
Converting a Fraction to %
Numerical Analysis 1 EE, NCKU Tien-Hao Chang (Darby Chang)
CSE20 Lecture 15 Karnaugh Maps Professor CK Cheng CSE Dept. UC San Diego 1.
Clock will move after 1 minute
famous photographer Ara Guler famous photographer ARA GULER.
Topic 16 Sorting Using ADTs to Implement Sorting Algorithms.
Physics for Scientists & Engineers, 3rd Edition
Select a time to count down from the clock above
Copyright Tim Morris/St Stephen's School
1.step PMIT start + initial project data input Concept Concept.
1 Dr. Scott Schaefer Least Squares Curves, Rational Representations, Splines and Continuity.
1 Non Deterministic Automata. 2 Alphabet = Nondeterministic Finite Accepter (NFA)
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Presentation transcript:

Chapter 11 Array-Based Lists

Knowledge Goals Understand the list abstraction and basic list operations Recognize the difference between an array and a list Understand how to use an array to represent a list Know how to use a key to establish the order of a sorted list Understand the principle of "divide and conquer" as expressed in the binary search algorithm

Skill Goals Add an item to a list Remove an item from a list Search for an item in a list Sort the items in a list into ascending or descending order Build a list in sorted order Search for an item in a sorted list using a linear search

Skill Goals Search for an item using a binary search Define a class that extends a Java interface Use Java's Comparable interface Use ArrayList from the Java library

What is a List? List A homogeneous collection of elements, with a linear relationship between the elements Linear relationship Every element (except the first) has a unique predecessor, and every element (except the last) has a unique successor Length (size in Java) The number of items in a list; it can vary over time

What is a List? Sorted list: The predecessor and successor relation- Key Key Sorted list: The predecessor and successor relation- ships are determined by the content of the keys

We are concerned only with unique keys What is a List? We are concerned only with unique keys

A List Class Can you name some of the operations that must be applied to a List?

A List Class

A List Class add remove isEmpty isFull size contains hasNext resetList Transformers add remove Observers isEmpty isFull size contains hasNext Iterators resetList next change state observe state process components

A List Class Attributes number of elements in list numItems listItems[0] . . . listItems[listItems.length-1] currentPos number of elements in list array of list elements used by iterator

A List Class

Class ListOfStrings is unsorted A List Class Class ListOfStrings is unsorted UNSORTED LIST Elements are placed into the list in no particular order with respect to their content SORTED LIST List elements are in an order that is sorted by the content of their keys -- either numerically or alphabetically

A List Class constructors public ListOfStrings() { numItems = 0; listItems = new String[100]; currentPos = 0; } public ListOfStrings(int maxItems) listItems = new String[maxItems]; constructors

A List Class observers public boolean isEmpty() { return (numItems == 0) } public int size() return numItems; public boolean isFull() return (numItems == listItems.length); observers

A List Class See why this works? public boolean contains(String item) { int index = 0; while (index < numItems && listItems[index].compareTo(item) != 0) index++; return (index < numItems); } See why this works?

Add: Does it matter where we put the item? Place the item in numItems location and increment numItems numItems 3 listItems [ 0 ] 15 [ 1 ] 39 [ 2 ] -90 [ 3 ] . . . [ listItems.length-1 ] item 63

After Inserting 64 into an Unsorted List numItems 4 listItems [ 0 ] 15 [ 1 ] 39 [ 2 ] -90 [ 3 ] 64 . . . [ listItems.length-1 ] item 64

A List Class public void add(String item) // Result: If the list is not full, puts item as // the last position in the list; otherwise list // is unchanged { if (!isFull()) listItems[numItems] = item; numItems++; }

A List class Remove is more difficult remove(item) Search (item, found, index) if (found) Shift remainder of list up Decrement numItems ShiftUp for count going from index downTo numItems Set listItems[count] to listItems[count+1]

Can you walk through deleting 39? numItems 4 listItems [ 0 ] 15 [ 1 ] 39 [ 2 ] -90 [ 3 ] 64 . [ listItems.length-1 ]

The List Class public void remove(String item) { int index = 0; boolean found = false; while (index < numItems && !found) if (listItems[index].compareTo(item) == 0) found = true; else index++; } if (found) for (int count = index; count < numItems - 1; count++) listItems[count] = listItems[count + 1]; numItems--;

A List Class Read documentation carefully! public void resetList() { currentPos = 0; } public boolean hasNext() { return (currentPos != numItems); } public String next() // Returns the item at the currentPos position // Assumptions: No transformers are called during the // iteration { String next = listItems[currentPos]; currentPos++; return next; } Read documentation carefully!

A List Class How are CRC cards and UML diagrams alike? they different?

A class is not complete until A List Class A class is not complete until it has been tested! Command-driven test driver A driver program that reads in commands and executes them; an excellent vehicle for unit testing a class enum Operations {ADD, REMOVE, SIZE, ISEMPTY, ISFULL, CONTAINS, PRINT, QUIT}

A List Class Main A Read file into list command- driven testing program Main Read file into list Set operation to inOperation() Set keepGoing to true while (keepGoing) Execute operation Set operation to inOperation Write list to file

A List Class executeOperation switch(operation) case ADD: // execute add case REMOVE: // execute remove case SIZE: // execute size case ISEMPTY: // execute isEmpty case ISFULL: // execute isFull case CONAINS: // execute contains case PRINT: // print list case QUIT: // quit How are resetList, hasNext, and next tested ?

ListWithSort Sorting Arranging the components of a list into order

ListWithSort Straight selection sort Examine the entire list to select the smallest element Swap that element with first element (with array index 0) Examine the remaining list to select the smallest element from it Swap that element with second element (array index 1) Continue process until only 2 items remain Examine the last 2 remaining list elements to select the smallest one Swap that element with the other

ListWithSort

ListWithSort Can you use the same test driver ?

A Sorted List Is ListWithSort the same as a SortedList? Are the same operations needed for a List and a SortedList? Any extra ones needed? From the client's (user's) point of view, what is the visible difference between an unsorted list and a sorted list?

A Sorted List

A Sorted List Add

A Sorted List public void add(String item) { if (! isFull()) {// find proper location for new element int index = numItems - 1; while (index >= 0 && item.compareTo(listItems[index]) < 0) listItems[index + 1] = listItems[index]; index--; } listItems[index +1] = item; // insert item numItems++; }

A Sorted List remove and next must maintain order but they already do!

Searching Linear (sequential) search Search begins at the beginning of the list and continues until the item is found or the entire list has been searched Can searching be improved if the items are in sorted order?

That's better, but we can do better yet Searching 3 34 7 99 66 11 [0] [1] [2] [3] [4] [5] How many comparisons are needed to find 11? 67? 2? 100? 3 7 11 34 66 99 [0] [1] [2] [3] [4] [5] How many comparisons are needed to find 11? 67? 2? 100? That's better, but we can do better yet

Searching Binary search (list must be sorted) Search begins at the middle and finds the item or eliminates half of the unexamined items; process is repeated on the half where the item might be Say that again…

Searching

Searching Boolean Binary Search (first, last) If (first > last) return false Else Set middle to (first + last)/2 Set result to item.compareTo(list[middle]) If (result is equal to 0) return true If (result < 0) Binary Search (first, middle - 1) Binary Search (middle + 1, last)

Searching Searching for "bat"

Searching

Searching public boolean isThere(String item) // Assumption: List items are in ascending order // Returns true if item is in the list; false otherwise { int first = 0; int last = numItems - 1; int middle; boolean found = false; while (last >= first && !found) { middle = (first + last) / 2; if (item.compareTo(listItems[middle]) == 0) found = true; // Item has been found else if (item.compareTo(listItems[middle] < 0) last = middle - 1; // Look in first half else first = middle + 1; // Look in second half } return found;

Searching Length Sequential Binary 10 5.5 2.9 100 50.5 5.8 1,000 500.5 Average Number of iterations Length Sequential Binary 10 5.5 2.9 100 50.5 5.8 1,000 500.5 9.0 10,000 5000.5 12.0 Is a binary search always better?

Refactoring the List Hierarchy Modifying code to improve its quality without changing is functionality There is a better way!

Refactoring the List Hierarchy public abstract class AbstractList { public AbstractList() public AbstractList(int maxItems) public boolean isFull() public boolean isEmpty() public int size() public void resetList() public boolean hasNext() public String next() public boolean contains(String item) public abstract void remove(String item) public abstract void add(String item) } What about contains?

Refactoring the List Hierarchy

List of Comparable Objects Wouldn't it be nice if we could have one abstract class for any data type, not one for each type of item that could be on the list? You can if you declare the type of the items to be Comparable protected Comparable[] listItems

List of Comparable Objects public abstract class AbstractList { public AbstractList() public AbstractList(int maxItems) public boolean isFull() public boolean isEmpty() public int size() public void resetList() public boolean hasNext() public String next() public boolean contains(Comparable item) public abstract void remove(Comparable item) public abstract void add(Comparable item) }

List of Comparable Objects public AbstractList() { numItems = 0; listItems = new Comparable[100]; currentPos = 0; } Abstract class public void add(Comparable item) { if (!isFull()) listItems[numItems] = (String) item; numItems++; } Derived class

Preview of Java Collections A collection of interfaces, abstract classes, and classes available in java.util that describe data structures available for you to use Why do you think we covered array-based lists before mentioning the Java Collections?

Preview of Java Collections ArrayList<type>(int number) Returns an array with an initial capacity of number elements. add(Object anObject) anObject is appended to the end of the list size() Returns the number of elements remove(Oject anObject) Removes an instance of anObject if it is there isEmpty Returns true of the list contains no elements contains(Object, anObject) Returns true if anObject is in the list iterator() Returns an Iterator over the elements of the list Plus lots more that are different

Preview of Java Collections import java.util.*; import java.io.*; public class ListDriver { private static Scanner inFile; private static PrintWriter outFile; public static void main(String[] args) throws IOException inFile = new Scanner(new FileReader("list.dat")); outFile = new PrintWriter(new FileWriter("list.out")); ArrayList list = new ArrayList(4); String line; different

Preview of Java Collections while (inFile.hasNextLine()) { line = inFile.nextLine(); list.add(line); } // Declare and instantiate iterator Iterator iterator = list.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); inFile.close(); outFile.close(); different look closely

Extras - GUI Track

Extras - GUI Track Handling events from multiple sources with panels requires declaring and instantiating a JPanel object setting the layout manager for the panel doing everything necessary to create a button adding the button to the panel declaring and instantiating multiple objects of the class with the panel

Extras - GUI Track Three instances of class containing panel

Extras - GUI Track Handling events from multiple sources with the same listener requires doing everything necessary to create multiple buttons handler gets a button's name from actionPerformed parameter handler uses if statement to determine which button was pressed

Extras - GUI Track Window with three buttons and one listener