Assignment #6: 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.

 

(Some exercise if you want to go further: try to experimentally determine the order of magnitude of this algorithm. As we know, it should be between O(log n) and O(n)).

 

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, deleting the minimum, might create a tree structure that is heavily imbalanced. Even more so, creating the tree is only an O(log n) operation under the same conditions. A BST is a versatile data structure for data retrieval, 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: Sunday 3/25 for 10 points, one more week for 6 points (go for the 10. This one is really simple).