ADT Table
- table operations
- keyed items
- table implementations:
- sorted array
- binary search tree
ADT Table
- data:
- rows and columns of a table
- the first column holds the keys
- each row belongs together
ID | exam 1 | exam 2 | total |
1 | 53 | 57 | 110 |
2 | 99 | 12 | 111 |
3 | 89 | 88 | 177 |
|
- insert
- delete
- retrieve by key
- traverse -- sorted or unsorted
Keyed Items
public abstract class KeyedItem {
private Comparable searchKey;
public KeyedItem (Comparable key) {
searchKey = key;
}
public Comparable getKey () {
return searchKey;
} }
public class City extends KeyedItem {
// the city is the searchKey
private String country; private int pop;
public City (String name, String land,
int count) {
super (name);
country = land; pop = count;
}
public String toString () {
return getKey() + ", " + country
+ ", " + pop;
Table Interface
public interface TableInterface {
// invariant: no two items in the
// in the table have the same key
public boolean isEmpty ();
public int length ();
public KeyedItem
retrieve (Comparable key);
// insert throws exception if the key
// is already present
public void insert (KeyedItem item)
throws TableException;
// returns true for succesful deletion
public boolean delete (Comparable key);
}
Table Implementations
- unsorted array based: insertion is O(1), retrieval and deletion O(n)
- sorted array based: retrieval is O(1), insertion and deletion O(n)
- unsorted reference based: insertion is O(1), retrieval and
deletion O(n)
- sorted reference based: everything is O(n)
- binary search tree: everything is O( log n) average,
O(n) worst case
- traversal is O(n) for all implementations
Sorted Array Implementation
public class TableArrayBased
implements TableInterface {
final int MAX = 100;
protected KeyedItem [] items;
private int size;
protected int position (Comparable k) {
//return 0..size (size only if not found)
}
public KeyedItem
retrieve (Comparable k) {
int p = position (k);
int pk = items [p].getKey ();
if ((p < size) &&
(k.compareTo (items[p].getKey ())
== 0)) {
return items [p];
} else {
return null;
} } }
Sorted Array Insertion
public void insert (KeyedItem item) {
int p = position (item);
if (p < size) {
Comparable k = item.getKey ();
Comparable pk = items[p].getKey ();
if (k.compareTo (pk) == 0)
throw new TableException ("dup");
}
if (size == MAX)
throw new TableException ("full");
for (int i = size - 1; i >= p; i++)
items [i + 1] = items [i];
items [p] = item;
size++;
}
}
Binary Search Tree Implementation
public class TableBSTBased
implements TableInterface {
protected BinarySearchTree [] tree;
protected int size;
public KeyedItem
retrieve (Comparable k) {
return tree.retrieve (k);
}
public void insert (KeyedItem item) {
if (tree.retrieve (item.getKey ())
!= null)
throw new TableException ("dup");
tree.insert (item); size++;
}
public void delete (Comparable k) {
try { tree.delete (item.getKey ());
} catch (TreeException e)
{ return false; }
size--; return true; } }