|
| 1 | +package sort; |
| 2 | + |
| 3 | +import static sort.SortUtils.less; |
| 4 | +import static sort.SortUtils.print; |
| 5 | + |
| 6 | + |
| 7 | +public class BinaryTreeSort{ |
| 8 | + |
| 9 | + interface TreeVisitor<T extends Comparable<T>> { |
| 10 | + void visit(Node<T> node); |
| 11 | + } |
| 12 | + |
| 13 | + private static class SortVisitor<T extends Comparable<T>> implements TreeVisitor<T> { |
| 14 | + |
| 15 | + private final T[] array; |
| 16 | + private int counter; |
| 17 | + |
| 18 | + SortVisitor(T[] array) { |
| 19 | + this.array = array; |
| 20 | + } |
| 21 | + |
| 22 | + @Override |
| 23 | + public void visit(Node<T> node) { |
| 24 | + array[counter++] = node.value; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + private static class Node<T extends Comparable<T>>{ |
| 29 | + private T value; |
| 30 | + private Node<T> left; |
| 31 | + private Node<T> right; |
| 32 | + |
| 33 | + Node(T value) { |
| 34 | + this.value = value; |
| 35 | + } |
| 36 | + |
| 37 | + void insert(Node<T> node) { |
| 38 | + if (less(node.value, value)){ |
| 39 | + if (left != null) left.insert(node); |
| 40 | + else left = node; |
| 41 | + } |
| 42 | + else { |
| 43 | + if (right != null) right.insert(node); |
| 44 | + else right = node; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + void traverse(TreeVisitor<T> visitor) { |
| 49 | + if ( left != null) |
| 50 | + left.traverse(visitor); |
| 51 | + |
| 52 | + visitor.visit(this); |
| 53 | + |
| 54 | + if ( right != null ) |
| 55 | + right.traverse(visitor ); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + private <T extends Comparable<T>> T[] sort(T[] array) { |
| 62 | + |
| 63 | + Node<T> root = new Node<>(array[0]); |
| 64 | + for (int i = 1; i < array.length; i++) { |
| 65 | + root.insert(new Node<>(array[i])); |
| 66 | + } |
| 67 | + |
| 68 | + root.traverse(new SortVisitor<>(array)); |
| 69 | + |
| 70 | + return array; |
| 71 | + |
| 72 | + } |
| 73 | + |
| 74 | + |
| 75 | + public static void main(String args[]) { |
| 76 | + |
| 77 | + Integer[] intArray = {12, 40, 9, 3, 19, 74, 7, 31, 23, 54, 26, 81, 12}; |
| 78 | + BinaryTreeSort treeSort = new BinaryTreeSort(); |
| 79 | + Integer[] sorted = treeSort.sort(intArray); |
| 80 | + print(sorted); |
| 81 | + |
| 82 | + Double[] decimalArray = {8.2, 1.5, 3.14159265, 9.3, 5.1, 4.8, 2.6}; |
| 83 | + print(treeSort.sort(decimalArray)); |
| 84 | + |
| 85 | + String[] stringArray = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"}; |
| 86 | + print(treeSort.sort(stringArray)); |
| 87 | + } |
| 88 | + |
| 89 | +} |
| 90 | + |
0 commit comments