Assignment #9: Binary Search Tree Sorting
First:
this assignment has no graphics, and, compared to the previous assignments, has
less hidden traps. I think it doesn’t have any, but I thought so about the
previous ones, too, so don’t trust me on that.
Second:
it is just an exercise, its practical value is questionable (however, the
question that arises from this assignment is exactly the motivation for the
next data structure in class, heaps).
That
said, here it is.
Create a
sequence of random numbers and sort them, using a binary search tree (BST).
This can be described in 2 ½ steps:
·
Build the tree
·
Delete the tree: (a) find the minimal element (and store it), (b) remove
it from the tree.
What you
need is:
·
A node class for the tree nodes, you build your data structure yourself.
Don’t try to use any JAVA tree implementations. For this assignment, it is much
easier to just create your little own specific tree class.
·
An insert(double value) method
·
A method public double removeMinimum()
Having
these classes, generate 30 random numbers and insert them into your tree. Then,
subsequently, call your removeMinimum method, and store the result (List or
array, I don’t care). When the tree is empty, print the stored numbers. They
should be sorted.
====
For 4
Bonus points, you can go further: automatically DRAW THE CURVE OF TIME
BEHAVIOUR of this algorithm. For this, BST-sort a changing (possibly high)
number of doubles (I would guess, you will have to start with about 10000, it depends
on your computer) and draw the curve runtime (=y axis) vs number of data
elements (= x axis).
Before
you start coding: think. The insert method is straightforward. The find and
delete method is easier than you might think at the beginning: the minimum
element is the leftmost element in the tree, i.e. it has no further left
children. This means, that for deletion, the min-node has zero or one children,
which is a very simple case for deletion.
IMPORTANT!
I
mentioned that this assignment has no high practical value. The reason is, that
a binary search tree is not the optimal data structure for this task. Finding
the minimum is an O(log n) operation only if the tree is balanced. But creating
and deleting might create a tree structure that is heavily imbalanced. A BST is
a versatile data structure for data retrieval. Yet to look for the minimum
only, it is too general. There is a data structure for this specific task,
called a heap. We’ll talk about it later. So: if you are in an interview, do
not argue for binary search trees when it comes to sorting!
That’s
it.
Deadline:
Tuesday 11/13 for 10 points, 11/20 for 6 points. Go for 10. It’s simple.