Storing the Fish: Binary Search Tree Programming Assignment A



Using a vector to store the fish solves the problem of an unbounded fish grid and provides efficient lookup time using binary search.  However, it does not perform as well for a dynamic fish population where fish are frequently added (from breeding) and removed (from dying).  In the case of frequent insertions and deletions, the need in a vector to open space in the vector for an insertion or to close space for a deletion makes these algorithms take O(N) time when there are N fish.  We need another approach for the combination of an unbounded fish grid and a dynamic population.

We can get efficient algorithms both for finding and for inserting fish into the set if we use a binary search tree.  This representation has performance comparable to binary search, O(log N), for finding a fish and similar performance for inserting and deleting fish.  Thus we get good performance even if the fish population is dynamic, and there is no dependence on a bounded grid.

We define a fish set class that is implemented using a binary search tree, ordered by position.  For example, in the diagram below we represent a 5x5 grid of fish, with fish located at positions (0,3), (2,1), (2,3), (3,1), (3,2), (4,4).


The functions in the Environment class that previously accessed the apmatrix of fish will access this set instead.  Analysis shows that with a dynamic population the complexity of some of the Environment functions, and therefore the Fish functions, is reduced compared to the vector model .


Start with the program created for the programming assignment Predator/Prey. Duplicate your PredatorPrey folder and call it BST.

  1. We need to overload operator < and operator != for the Position class, so that these comparisons can be used when searching in the lookup table ordered by position.
  2. Construct a Directory (i.e. Lookup Table or Map) class that stores items with a key.  We can do this as a template class with two placeholders for types, one for the items to be stored (ItemType) and the other for the keys (KeyType). KeyType must have operator <  defined for it.  In our case KeyType will be Position.
  3. The BST.h file contains the class declaration for a BST implemented directory.  The BST.cpp file contains a partial implementation of Directory.  The following functions remain to be implemented in directoryBST.cpp.  These are all best done recursively.
  4. After the directory based on a binary tree is done, we need to replace the apmatrix myWorld with a Directory in the fish Environment class.
  5. The following Environment functions need to be changed to use the Directory for accessing fish instead of the apmatrix.