A Binary Tree Sort is an algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order.
Average Case Time Complexity : O(N log N) adding one element to a Binary Search Tree on average takes O(log N) time (height of a tree). Therefore, adding n elements will take O(N log N) time.
Worst Case Time Complexity : O(N^2). The worst case can be improved by using a self-balancing binary search tree, which will take O(N log N) time to sort the array in worst case.
Just for practicing, I've implemented the Binary Tree Sort algorithm, and if you'd like to review the code and provide any change/improvement recommendations, please do so, and I appreciate that.
Code
""" This module creates a Binary Sort Tree ascendingly using In Order Tree Traverse; Stable Sort; Worst Case Time Complexity (For if the tree would be a chain Tree): O(N^2) Average Case Time Complexity: O(N^Log N) Memory Complexity: Not in place O(N) """ import random from typing import List, TypeVar T = TypeVar('T') # Not sure how to design and handle the exceptions here yet class ExceptionHandling(Exception): pass class Node(object): def __init__(self, node_value: int) -> None: """ Initializes a node with three attributes; `node_value` (Node Value): Must be an integer/float; `right_child` (Right Child): Initializes to `None`; Its value must be larger than the Root Node; `left_child` (Left Child): Initializes to `None`; Its value must be smaller than the Root Node; """ self.node_value = node_value self.right_child = None self.left_child = None class BinarySearchTree(object): def __init__(self) -> None: """ Initializes the Root Node of the Binary Tree to None; """ self.root = None def is_empty(self) -> bool: """ Returns True if the tree doesn't have a node; """ return self.root == None def insert(self, new_node: int) -> None: """ Inserts an integer-value Node in the Tree; """ self.root = self._insert(self.root, new_node) def _insert(self, parent: int, new_node: int) -> int: """ Inserts an integer value in the left or right Node; Returns the parent Node; """ # If tree is empty if parent is None: parent = Node(new_node) # If the new Node value is smaller than its parent Node value elif new_node < parent.node_value: parent.left_child = self._insert(parent.left_child, new_node) # If the new Node value is bigger than its parent Node value else: parent.right_child = self._insert(parent.right_child, new_node) return parent def inorder(self) -> None: """ Calls the _inorder traversing method; """ self._inorder(self.root) def _inorder(self, parent: int) -> None: """ Traverses the tree inorder (Left Node, Root Node, Right Node) """ if parent is None: return self._inorder(parent.left_child) print(f'{parent.node_value}') self._inorder(parent.right_child) if __name__ == '__main__': tree = BinarySearchTree() for i in range(random.randint(20, 30)): tree.insert(random.uniform(-10, 10)) tree.inorder()