Download presentation

Presentation is loading. Please wait.

Published byMia Connolly Modified over 4 years ago

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

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

3
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)

4
S. Xu 4 ADT Table Dictionary Member Record keystudent namehw1... 123Stan Smith49... 124Sue Margolin56... 125Billie King34... 167Roy Miller39...

5
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

6
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

7
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

8
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

9
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

10
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

11
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( ))

12
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

13
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

14
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

15
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

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

17
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

18
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

19
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

20
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?

21
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?

22
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

23
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

24
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)

25
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

26
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; }

27
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

28
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

29
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

30
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

31
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

32
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

33
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

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

35
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()); }

Similar presentations

OK

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)

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)

© 2018 SlidePlayer.com Inc.

All rights reserved.

To make this website work, we log user data and share it with processors. To use this website, you must agree to our Privacy Policy, including cookie policy.

Ads by Google

Ppt on 4-stroke petrol engines Ppt on indian politics quotes Ppt on essay writing Ppt on success and failure articles Ppt on event management system Ppt on wildlife and vegetation conservation Ppt on recycling of waste material Ppt on endangered species of plants Ppt on aircraft landing gear systems Ppt on 3g mobile technology download