Algorithms and OOD (CSC 207 2014F) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [Learning Outcomes] [FAQ] [Teaching & Learning] [Grading] [Rubric] - [Calendar]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines] [Readings]
Reference: [Student-Curated Resources] [Java 8 API] [Java 8 Tutorials] [Code Conventions]
Related Courses: [CSC 152 2006S (Rebelsky)] [CSC 207 2014S (Rebelsky)] [CSC 207 2014F (Walker)] [CSC 207 2011S (Weinman)]
Misc: [Submit Questions] - [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Issue Tracker (Course)] [Issue Tracker (Textbook)]
Overview
You have to implement dictionaries in the next two hours. You don't get to use the java.util.* stuff. What do you do?
Create a class, KeyValuePair, that holds a key and a value. Make an array of those.
public class KeyValuePair<K,V>
{
K key;
V value;
} // KeyValuePair<K,V>
public class AssociativeArray<K,V>
implements Dictionary<K,V>
{
// +-------+-------------------------------------------------------
// | Notes |
// +-------+
/*
We store key/value pairs in the locations of an array.
We have some blank spots, all of which congregate at the
end.
We know how many spots are useful through the variable size.
*/
// +--------+------------------------------------------------------
// | Fields |
// +--------+
KeyValuePair<K,V>[] pairs; // Capacity is pairs.length
int size; // The number of key/value pairs in the array
// +---------+-----------------------------------------------------
// | Methods |
// +---------+
public V get(K key)
{
for (int i = 0; i < size; i++)
{
if (k.equals(pairs[i].key))
return pairs[i].value;
} // for
return null;
} // get(K)
public void add(K key, V value)
{
} // add(K, V)
} // AssociativeArray<K,V>
Can we do better than O(n) for all of the operations? Suppose we want
get to be less than O(n), but we're okay with add and remove
being O(n)?
Strategy:
Strategy:
Break up the data into parts
public class Node<K,V>
{
K key;
V value;
Node<K,V> smaller; // Things with smaller keys
Node<K,V> larger; // Things with larger keys
}
If we can arrange the tree in advance, we have O(logn) get
How do we keep them balanced? Take 301