COSC2007 Data Structures II
Chapter 11
Tables &
Priority Queues I
S. Xu2
Topics
Tables Operation Implementation
Array-based BST-based
S. Xu3
ADT Table
Table example: City population
City (key) Country Population(sorted)Athens Greece 2,500,000Barcelona Spain 1,800,000Cairo Egypt 16,500,000London England 9,400,000New York U.S.A 7,300,000Paris France 2,200,000Toronto Canada 3,200,000Venice Italy 300,000
Questions What is the population of London? (uses key - binary search) Which city is in Italy? (can’t use key – sequential search)
S. Xu4
ADT TableDictionary
MemberRecord
key student name hw1
...123 Stan Smith 49
...124 Sue Margolin 56
...125 Billie King 34
...167 Roy Miller 39
...
S. Xu5
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. Xu6
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. Xu7
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. Xu8
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. Xu9
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. Xu10
ADT Table Example: Populations
public class City extends KeyedItem{
private string country; //city name will be the searchKeyprivate int Pop;public City (String theCity, String theCountry, int newPop ) {
super (theCity);country = theCountry;pop=newPop;
} // constructorspublic string toString () {
return getKey()+”, “ +country+” “ + pop;}
// other methods } // end City class
S. Xu11
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. Xu12
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. Xu13
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. Xu14
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. Xu15
ADT Table Implementation
Example Sorted (by search key)
Array based
reference based
Athens Barcelona . . . Venice . . .9
size 0 1 size-1 MAX_TABLE -1
Athens Barcelona Venice•9
size head
S. Xu16
ADT Table
Implementation Using ADT BST
New York
Cairo
VeniceParisLondonBarcelona
RomeAthens
Toronto
9
size
S. Xu17
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. Xu18
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. Xu19
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 ...
Athens Barcelona Venice•K+1
New item
S. Xu20
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. Xu21
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. Xu22
Scenario C: Insertion, Deletion, Retrieval, & Traversal - Sorted Order
Insertion for sorted linear implementation Array-based
Reference-based
New item
Data Data . . . DataK+1
items 0 i-1 i i+1 K . . .
Data Data Data•New item
Data
head
S. Xu23
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 Log2 (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. Xu24
Comparison of Time Complexity (average)Operation Insertion Deletion Retrieval Traversal
Unsorted Array O(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. Xu25
ADT Table's Sorted Array-Based Implementation
public interface TableInterface {
public boolean tableIsEmpty();// Determines whether a table is emptypublic int tableLength( );// Determines the number of items in a tablepublic 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. Xu26
ADT Table's Sorted Array-Based Implementation
//one item with a given search key at any timepublic class TableArrayBased implements TableInterface {
final int MAX_TABLE = 100; // maximum size of tableprotected KeyedItem [] items; //table itemprivate int size; //table size
public TableArrayBased() {items = new KeyedItem[MAX_TABLE];size =0;
} //default constructorpublic boolean tableIsEmpty() {
return size==0;}
Public int tableLength () {return size;
}
S. Xu27
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 keythrow 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. Xu28
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. Xu29
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
elsereturn null;
} // end tableRetrieve
S. Xu30
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<size) &&(searchKey.compareTo(item[pos].getKey())>0))
pos++;return pos
} // end position
} //end TableArrayBased
S. Xu31
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. Xu32
ADT Table's BST Implementationpublic class TableBSTBased implements TableInterface{ protected BinarySearchTree bst; // binary search tree that contains the table’s items protected int size; // number of items in the table
public TableBSTBased () {bst = new BinarySearchTree();size=0;
}
//table operationspublic boolean tableIsEmpty() {
return size==0;} //end tableIsEmpty
public int tableLength (){return size;
} //end tablelength
S. Xu33
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. Xu34
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. Xu35
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());}