Skip to content

Commit 4f6e63b

Browse files
committed
Add BinaryTreeSort algorithm
- Implements Binary Tree Sort using BST with inorder traversal - O(n log n) average case, O(n²) worst case time complexity - Includes comprehensive test suite extending SortingAlgorithmTest
1 parent 9484c7e commit 4f6e63b

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.thealgorithms.sorts;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Binary Tree Sort Algorithm Implementation
8+
*
9+
* @see <a href="https://en.wikipedia.org/wiki/Tree_sort">Binary Tree Sort Algorithm</a>
10+
*/
11+
public class BinaryTreeSort implements SortAlgorithm {
12+
13+
private static class TreeNode<T extends Comparable<T>> {
14+
T data;
15+
TreeNode<T> left;
16+
TreeNode<T> right;
17+
18+
TreeNode(T data) {
19+
this.data = data;
20+
this.left = null;
21+
this.right = null;
22+
}
23+
}
24+
25+
@Override
26+
public <T extends Comparable<T>> T[] sort(T[] array) {
27+
if (array == null || array.length <= 1) {
28+
return array;
29+
}
30+
31+
TreeNode<T> root = null;
32+
for (T value : array) {
33+
root = insert(root, value);
34+
}
35+
36+
List<T> result = new ArrayList<>();
37+
inorder(root, result);
38+
39+
for (int i = 0; i < array.length; i++) {
40+
array[i] = result.get(i);
41+
}
42+
43+
return array;
44+
}
45+
46+
private <T extends Comparable<T>> TreeNode<T> insert(TreeNode<T> root, T data) {
47+
if (root == null) {
48+
return new TreeNode<>(data);
49+
}
50+
51+
if (SortUtils.less(data, root.data)) {
52+
root.left = insert(root.left, data);
53+
} else {
54+
root.right = insert(root.right, data);
55+
}
56+
57+
return root;
58+
}
59+
60+
private <T extends Comparable<T>> void inorder(TreeNode<T> root, List<T> result) {
61+
if (root != null) {
62+
inorder(root.left, result);
63+
result.add(root.data);
64+
inorder(root.right, result);
65+
}
66+
}
67+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.thealgorithms.sorts;
2+
3+
public class BinaryTreeSortTest extends SortingAlgorithmTest {
4+
@Override
5+
SortAlgorithm getSortAlgorithm() {
6+
return new BinaryTreeSort();
7+
}
8+
}

0 commit comments

Comments
 (0)