Tree Sort (BST Sort)
Builds BST from elements, then in-order traversal gives sorted output.
Visualization
Interactive visualization for Tree Sort (BST Sort)
Interactive visualization with step-by-step execution
Implementation
1function treeSort(arr: number[]): number[] {
2 class Node { val: number; left: Node | null = null; right: Node | null = null; constructor(v: number) { this.val = v; } }
3 let root: Node | null = null;
4 const insert = (node: Node | null, val: number): Node => {
5 if (!node) return new Node(val);
6 if (val < node.val) node.left = insert(node.left, val);
7 else node.right = insert(node.right, val);
8 return node;
9 };
10 const inorder = (node: Node | null, result: number[]) => {
11 if (!node) return;
12 inorder(node.left, result);
13 result.push(node.val);
14 inorder(node.right, result);
15 };
16 for (const val of arr) root = insert(root, val);
17 const result: number[] = [];
18 inorder(root, result);
19 return result;
20}Deep Dive
Theoretical Foundation
Insert all elements into BST, then in-order traversal retrieves sorted order. Balanced BST guarantees O(n log n).
Complexity
Time
O(n log n)
O(n log n)
O(n²)
Space
O(n)
Applications
Industry Use
When BST already needed
Online sorting
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.