Tree sort

Tree sort is an algorithm that builds a tree, generally a binary tree, for each element in the array, and then traverses the tree in-order to produce the sorted array.

Algorithm
There are many different types of trees, but this section will focus only on a simple, unbalanced binary search tree.

A structure is defined, called a node, which contains the object, then the left and right child node. Initially there is a single node, as the basis called the root, which contains the first element, and does not have any left and right children yet. Then the following elements in the array are inserted from the tree.

To insert an element to the array, check if the element to be inserted is greater than or equal to the element of the current node, initially the root node. If so, move to its right child, otherwise move to its left child. Repeat this process until a node that does not exist has been reached. Then put the node in there, with the corresponding element. Return this node so that the parent can connect it.

After all elements have been inserted to the tree, do an in-order traversal. Start from the root node. For each node, recursively traverse its left child, then put the current node's object into the array, then recursively traverse its right child.

Pseudocode
structure Node elem element Node left Node right end procedure insert(Node node, elem element) do if node == NULL then Node newNode = Node(element, NULL, NULL) return newNode else if node:element >= element then node:left = insert(node:left, element) else node:right = insert(node:right, element) end if return node end if end # 'track' is used to keep track of what current index to be placed on the array procedure traverse(array arr, Node node, int track = 0) do if node == NULL then return track else track = traverse(arr, node, track) arr[track] = node:element track = traverse(arr, node, track + 1) return track end if end procedure tree_sort(array arr) do Node root = Node(arr[0], NULL, NULL) for index = 1 to length(arr) - 1 do insert(root, arr[index]) end for traverse(arr, root) end