package sort;
import java.util.ArrayList;
/*
* Sorts via a tree which can be more reliably quick than quicksort
*
* Worst Case: O(n^2)
* Average/ Best Case: O(nlogn)
*
* aevans 9.9.2013
*/
public class TreeSort<E extends Comparable> {
private ArrayList<E> list;
private TreeNode<E> root;
private TreeNode<E> temp;
private TreeNode<E> newNode;
private ArrayList<E> sorted;
public TreeSort() {
// TODO empty constructor
}
public TreeSort(ArrayList<E> inlist) {
// TODO constructor with list
list = inlist;
}
public void setList(ArrayList<E> inlist) {
// TODO set the list
list = inlist;
}
public void setSorted(ArrayList<E> insorted) {
// TODO set the sorted list
sorted = insorted;
}
public ArrayList<E> getList() {
// TODO return the list
return list;
}
public ArrayList<E> getSorted() {
// TODO return the sorted list
return sorted;
}
public void resetTree() {
// TODO reset the tree
root = null;
sorted = null;
}
public ArrayList<E> sort() {
// TODO perform the sort by placing elements in the tree
for (E val : list) {
// create the tree
if (root == null) {
// root is null set root and set temp to root for connection
root = new TreeNode<E>(val, null, null, null);
temp = root;
} else {
insert(val);
}
}
// sort;
sorted = null;
createSorted();
return sorted;
}
public void insert(E val) {
// TODO perform the recursive insertion into the tree
if (temp.getValue().compareTo(val) <= 0) {
if (temp.getClass() != null) {
temp = temp.getLeft();
insert(val);
} else {
newNode = new TreeNode<E>(val, null, null, temp);
temp.setLeft(newNode);
}
} else {
if (temp.getRight() == null) {
newNode = new TreeNode<E>(val, null, null, temp);
temp.setRight(newNode);
} else {
temp = temp.getRight();
insert(val);
}
}
}
private void printNodes(TreeNode<E> inNode) {
// TODO add Nodes to list in order
if (temp != null) {
printNodes(inNode.getLeft());
}
if (temp != null) {
printNodes(inNode.getRight());
}
sorted.add(temp.getValue());
}
public void createSorted() {
// TODO post-order printing of a sorted list from the tree
printNodes(root);
}
}