COSC2007 Data Structures II Chapter 11 Tables & Priority Queues I.

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

COSC 2007 Data Structures II Chapter 12 Advanced Implementation of Tables III.
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Chapter 1 The Study of Body Function Image PowerPoint
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Chapter 7. Binary Search Trees
Chapter 17 Linked Lists.
COMP171 Fall 2005 Lists.
Chapter 4 Linked Lists. © 2005 Pearson Addison-Wesley. All rights reserved4-2 Preliminaries Options for implementing an ADT List –Array has a fixed size.
Singly Linked Lists What is a singly-linked list? Why linked lists?
David Luebke 1 6/7/2014 ITCS 6114 Skip Lists Hashing.
Linked Lists Chapter 4.
Chapter 10: Applications of Arrays and the class vector
Data Structures: A Pseudocode Approach with C
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
11 Data Structures Foundations of Computer Science ã Cengage Learning.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 4: Linked Lists Data Abstraction & Problem Solving with.
1 CSE1301 Computer Programming: Lecture 27 List Manipulation.
Abstract Data Types and Algorithms
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
Data Structures Using C++
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Double-Linked Lists and Circular Lists
FIFO Queues CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
1 Joe Meehean. Ordered collection of items Not necessarily sorted 0-index (first item is item 0) Abstraction 2 Item 0 Item 1 Item 2 … Item N.
1 Designing Hash Tables Sections 5.3, 5.4, Designing a hash table 1.Hash function: establishing a key with an indexed location in a hash table.
The ADT Hash Table What is a table?
Hash Tables.
1 Symbol Tables Chapter Sedgewick. 2 Symbol Tables Searching Searching is a fundamental element of many computational tasks looking up a name.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
1 Undirected Breadth First Search F A BCG DE H 2 F A BCG DE H Queue: A get Undiscovered Fringe Finished Active 0 distance from A visit(A)
Review Pseudo Code Basic elements of Pseudo code
1 Breadth First Search s s Undiscovered Discovered Finished Queue: s Top of queue 2 1 Shortest path from s.
The List ADT Textbook Sections
© 2012 National Heart Foundation of Australia. Slide 2.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 11: Priority Queues and Heaps Java Software Structures: Designing.
25 seconds left…...
Equal or Not. Equal or Not
Slippery Slope
© 2006 Pearson Addison-Wesley. All rights reserved10 A-1 Chapter 10 Algorithm Efficiency and Sorting.
Foundations of Data Structures Practical Session #7 AVL Trees 2.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
© 2006 Pearson Addison-Wesley. All rights reserved12 A-1 Chapter 12 Tables and Priority Queues.
© 2006 Pearson Addison-Wesley. All rights reserved12-1 Chapter 12 Tables and Priority Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring.
Marc Smith and Jim Ten Eyck
COSC 2007 Data Structures II
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
© 2006 Pearson Addison-Wesley. All rights reserved12 A-1 Chapter 12 Tables and Priority Queues.
COSC 1030 Lecture 9 Binary Trees. Topics Basic Concept and Terminology Applications of Binary Tree Complete Tree Representation Traversing Binary Trees.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues I.
Prof. Amr Goneid, AUC1 CSCI 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 5. Dictionaries(2): Hash Tables.
Chapter 11 B Trees. © 2004 Pearson Addison-Wesley. All rights reserved 11 B-2 The ADT Binary Search Tree A deficiency of the ADT binary tree which is.
COSC2007 Data Structures II Chapter 11 Trees IV. 2 Topics ADT BST Implementations Efficiency TreeSort Save/Restore into/from file General Trees.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Prof. Amr Goneid, AUC1 CSCI 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 5. Dictionaries(2): Hash Tables.
Chapter 12 A Tables.
Trees Chapter 11 (continued)
Trees Chapter 11 (continued)
CS202 - Fundamental Structures of Computer Science II
Ch. 12 Tables and Priority Queues
Tables and Priority Queues
Presentation transcript:

COSC2007 Data Structures II Chapter 11 Tables & Priority Queues I

S. Xu 2 Topics Tables Operation Implementation Array-based BST-based

S. Xu 3 ADT Table Table example: City population City (key)CountryPopulation (sorted) AthensGreece 2,500,000 BarcelonaSpain 1,800,000 CairoEgypt16,500,000 LondonEngland 9,400,000 New YorkU.S.A 7,300,000 ParisFrance 2,200,000 TorontoCanada 3,200,000 VeniceItaly 300,000 Questions What is the population of London? (uses key - binary search) Which city is in Italy? (cant use key – sequential search)

S. Xu 4 ADT Table Dictionary Member Record keystudent namehw Stan Smith Sue Margolin Billie King Roy Miller39...

S. Xu 5 ADT Table ADT Table (Dictionary) Elements are records containing several pieces of information Value oriented Implementation Needs rapid retrieval of items Assumption: All items in a table have distinct search keys Some tables allow duplicate search keys Items should not be inserted if they already exist in the table

S. Xu 6 ADT Table Operations Create an empty table Destroy a table Determine whether a table is empty Insert new item into a table, if item not already in the table Delete an item with a given search key from a table Retrieve an item with a given search key from a table Traverse items in the table in sorted search-key order

S. Xu 7 ADT Table Operations Some operations can't be performed using the above operations Display all table items We can't retrieve an item without knowing its search key When traversing the table, we have to specify the order of traversal Visit the items sorted by search key Can not change the search-key for each item

S. Xu 8 ADT Table Example: Populations Which implementation will be best suited for each of the following operations? Display in alphabetical order, the name of each city & its population Increase the population of each city by 10 Delete all cities with population < 1,000,000

S. Xu 9 ADT Table Operations: KeyedItem Class public abstract class KeyedItem { private Comparable searchKey; public KeyedItem(Comparable key ) { searchKey = key; } public Comparable getKey() { return searchKey; } // end getKey } // end KeyedItem class Only one constructor is available, and not setKey () is defined

S. Xu 10 ADT Table Example: Populations public class City extends KeyedItem { private string country; //city name will be the searchKey private int Pop; public City (String theCity, String theCountry, int newPop ) { super (theCity); country = theCountry; pop=newPop; }// constructors public string toString () { return getKey()+, +country+ + pop; } // other methods }// end City class

S. Xu 11 ADT Table Example: Display in alphabetical order, the name of each city & its population The order of the visit is important Method to display an item should be passed as the Iterator +displayItem(anItem) Display anItem.cityName( ) Display anItem.getPopulation ( ) Increase the population of each city by 10 The order of the visit is not important Method to update the population should be passed as the Iterator +updatePopulation(anItem) anItem.setPopulation(1.1 * anItem.getPopulation( ))

S. Xu 12 ADT Table Example: Delete all cities with population < 1,000,000 The order of the visit is not important method to delete populations less than the desired should be passed as the iterator +deleteSmall(Table, anItem) if (anItem.getPopulation( ) < 1,000,000) t.tableDelete(anItem) Problem: Table changes (item is deleted) during traversal Difficult to program traversal algorithm

S. Xu 13 ADT Table Implementation Linear implementation of tables could be: Unsorted Array based Reference based Sorted (by search key) Array based Reference based Both implementations should maintain a count of the items in the table

S. Xu 14 ADT Table Implementation ADT Table can also be implemented using ADT list Sorted List BST The requirements of the particular application influence the selection of an implementation One implementation supports some of the operations more efficient than the other

S. Xu 15 ADT Table Implementation Example Sorted (by search key) Array based reference based Athens Barcelona... Venice... 9 size 01 size-1 MAX_TABLE -1 AthensBarcelonaVenice 9 size head

S. Xu 16 ADT Table Implementation Using ADT BST New York Cairo Venice ParisLondon Barcelona RomeAthens Toronto 9 size

S. Xu 17 ADT Table Implementation Factors affecting the selection of an implementation: Necessary operations Expected frequency of occurrence of each operation Required response times for the operations

S. Xu 18 Scenario A: Insert & Traverse (no Particular Order) Example: Raise money for local Charity Insert fund-raiser ideas into a table and later print a report Items can be sorted or unsorted No operation requires a specific order Maintaining items in a specific order has no advantage For array based implementation, insert items after the last item in the array (Big O??) For reference based implementation, insert items at the beginning of the linked list Big O?? tableInsert operation requires constant time for either implementation regardless of the size of the table

S. Xu 19 Scenario A: Insert & Traverse (no Particular Order) Insertion for unsorted linear implementation Array-based Reference-based Athens Barcelona... Venice... K+1 New item K-1 K K+1... AthensBarcelonaVenice K+1 New item

S. Xu 20 Scenario B: Retrieval Example: Word Processor's Thesaurus Frequent retrievals require table implementation that allows efficient searching for items, given a search key value No deletions or insertions are necessary For reference-based implementation, you must traverse the linked list from its beginning until the required word is found Binary search performs fast retrieval? What is the problem? Sorted array-based implementation will be more suitable A Balanced BST would also be suitable, why?

S. Xu 21 Scenario C: Insertion, Deletion, Retrieval, & Traversal - Sorted Order Example: Computerized Library Catalog Elements are sorted Retrieval is the most frequent operation Both insertion & deletion perform two steps: 1. Find the appropriate position in the table 2. Insert into (or delete from) this position We need both steps together. How about efficiency? If the table is sorted, both tableInsert & tableDelete will require amount of time ~ (O(N)) in either array or reference-based implementations More?

S. Xu 22 Scenario C: Insertion, Deletion, Retrieval, & Traversal - Sorted Order Insertion for sorted linear implementation Array-based Reference-based New item Data Data... Data K+1 items 0i-1i i+1 K... Data New item Data head

S. Xu 23 Conclusion Linear implementations Less sophisticated & generally require more time than BST implementation Appropriate for tables containing small number of items BST implementation Better if they have minimum height Height of BST depends on the order in which insertions & deletions are performed We can keep the height of the tree near Log 2 (N) by using the tree balancing algorithms Reference-based implementation of BST Permits dynamic allocation an can handle tables whose maximum size is unknown Efficiently perform insertions & deletions ADT Table is appropriate when you have a data base to maintain and search by value

S. Xu 24 Comparison of Time Complexity (average) Operation Insertion Deletion Retrieval Traversal Unsorted ArrayO(1)O(n) O(n)O(n) Unsorted reference O(1)O(n) O(n)O(n) Sorted Array O(n)O(n) O(logn)O(n) Sorted reference O(n)O(n) O(n)O(n) BST O(logn)O(logn) O(logn)O(n)

S. Xu 25 ADT Table's Sorted Array-Based Implementation public interface TableInterface { public boolean tableIsEmpty(); // Determines whether a table is empty public int tableLength( ); // Determines the number of items in a table public void tableInsert(KeyedItem newItem) throw TableException; public boolean tableDelete(Comparable searchKey); public KeyedItem tableRetrieve(Comparable SearchKey) ; } //end TableInterface class TableException extends Exception { public TableException(String message) { super ( message); } } // end TableException

S. Xu 26 ADT Table's Sorted Array-Based Implementation //one item with a given search key at any time public class TableArrayBased implements TableInterface { final int MAX_TABLE = 100; // maximum size of table protected KeyedItem [] items; //table item private int size;//table size public TableArrayBased() { items = new KeyedItem[MAX_TABLE]; size =0; } //default constructor public boolean tableIsEmpty() { return size==0; } Public int tableLength () { return size; }

S. Xu 27 ADT Table's Sorted Array-Based Implementation Public void tableInsert(KeyedItem newItem) throws TableException { // Note: Insertion is unsuccessful if the table is full, // that is, if the table already contains MAX_TABLE items. // Calls: position. if (size == MAX_TABLE) throw new TableException("TableException: Table full"); // there is room to insert; locate the position where newItem belongs int spot = position(newItem.getKey()); If ((spot<size) && (items[spot].getKey()).compareTo(newItem.getKey())==0) { //duplicate key throw new TableException("TableException: Duplicate Key item"); } Else { // shift up to make room for the new item for (int index = size-1; index >= spot; --index) items[index+1] = items[index]; // make the insertion items[spot] = newItem; ++size; } //end if } // end tableInsert

S. Xu 28 ADT Table's Sorted Array-Based Implementation public boolean tableDelete(Comparable SearchKey) { // Calls: Position. // locate the position where SearchKey exists/belongs int Spot = position(SearchKey); // is SearchKey present in the table? boolean success = (spot <= size) && (items[Spot].getKey().compareTo(SearchKey)==0); if (success) { // SearchKey in Table --Size; // delete the item // shift down to fill the gap for (int index = spot; index < size; ++index) items[index] = items[index+1]; } // end if return success; } // end tableDelete

S. Xu 29 ADT Table's Sorted Array-Based Implementation Public KeyedItem tableRetrieve(Comparable searchKey) { // Calls: position. // locate the position where SearchKey exists/belongs int spot = position(searchKey); // is searchKey present in table? boolean success = (spot <= size) && (items[spot].getKey().compareTo(searchKey)==0); if (success) return items[spot]; // item present; retrieve it else return null; } // end tableRetrieve

S. Xu 30 ADT Table's Sorted Array-Based Implementation protected int position(Comparable searchKey) { // find the position of a table item or insertion point int pos =0; while ((pos 0)) pos++; return pos } // end position } //end TableArrayBased

S. Xu 31 ADT Table's BST Implementation Linear implementation are not good for general-purpose of ADT table Non-linear (using BST) to represent the items in the table is better in most cases We can reuse BinarySearchTree class implemented in Chapter 10

S. Xu 32 ADT Table's BST Implementation public class TableBSTBased implements TableInterface { protected BinarySearchTree bst; // binary search tree that contains the tables items protected int size; // number of items in the table public TableBSTBased () { bst = new BinarySearchTree(); size=0; } //table operations public boolean tableIsEmpty() { return size==0; } //end tableIsEmpty public int tableLength (){ return size; } //end tablelength

S. Xu 33 ADT Table's BST Implementation public void tableInsert(KeyedItem newItem) throws TableException { if (bst.retrieve (newItem.getKey())==null) { bst.insert(newItem); ++size; } else throw new TableException("TableException: duplicate key item"); } // end tableInsert public KeyItem tableRetrieve(Comparable searchKey) { return bst.retrieve(searchKey); } // end tableRetrieve

S. Xu 34 ADT Table's BST Implementation public boolean tableDelete(Comparable searchKey) { try { bst.delete(searchKey); } // end try catch (TreeException e) { return false; } // end catch -- size; return true; } // end tableDelete protected void setSize (int newSize) { size = newSize; } // end setSize }// End of implementation file.

S. Xu 35 ADT Table's BST Implementation Test program public class TestTable { public statcic void main (String[] args) { TableInterface chart = new TableBSTBased (); City anItem; anItem = new City (Windsor, canada, 12000); chart.tableInsert (anItem); anItem = new City (Soo, Canada, 5000); chart.tableInsert(anItem); TableInteratorBST iter = new TableInteratorBST (chart); while (iter.gasNext()) displayCity ((City)iter.next()); } public static void displayCity (City anItem) { System.out.println (anItem.getCity()); }