diff --git a/src/main/java/com/thealgorithms/sorts/BinaryTreeSort.java b/src/main/java/com/thealgorithms/sorts/BinaryTreeSort.java new file mode 100644 index 000000000000..edc82abb08ba --- /dev/null +++ b/src/main/java/com/thealgorithms/sorts/BinaryTreeSort.java @@ -0,0 +1,67 @@ +package com.thealgorithms.sorts; + +import java.util.ArrayList; +import java.util.List; + +/** + * Binary Tree Sort Algorithm Implementation + * + * @see Binary Tree Sort Algorithm + */ +public class BinaryTreeSort implements SortAlgorithm { + + private static class TreeNode> { + T data; + TreeNode left; + TreeNode right; + + TreeNode(T data) { + this.data = data; + this.left = null; + this.right = null; + } + } + + @Override + public > T[] sort(T[] array) { + if (array == null || array.length <= 1) { + return array; + } + + TreeNode root = null; + for (T value : array) { + root = insert(root, value); + } + + List result = new ArrayList<>(); + inorder(root, result); + + for (int i = 0; i < array.length; i++) { + array[i] = result.get(i); + } + + return array; + } + + private > TreeNode insert(TreeNode root, T data) { + if (root == null) { + return new TreeNode<>(data); + } + + if (SortUtils.less(data, root.data)) { + root.left = insert(root.left, data); + } else { + root.right = insert(root.right, data); + } + + return root; + } + + private > void inorder(TreeNode root, List result) { + if (root != null) { + inorder(root.left, result); + result.add(root.data); + inorder(root.right, result); + } + } +} diff --git a/src/test/java/com/thealgorithms/sorts/BinaryTreeSortTest.java b/src/test/java/com/thealgorithms/sorts/BinaryTreeSortTest.java new file mode 100644 index 000000000000..b6df22851275 --- /dev/null +++ b/src/test/java/com/thealgorithms/sorts/BinaryTreeSortTest.java @@ -0,0 +1,8 @@ +package com.thealgorithms.sorts; + +public class BinaryTreeSortTest extends SortingAlgorithmTest { + @Override + SortAlgorithm getSortAlgorithm() { + return new BinaryTreeSort(); + } +}