Tree Sort

Builds a binary search tree and traverses it.

Best O(n log n) Avg O(n log n) Worst O(n^2) Space O(n) Stable Yes In-place No Comparison-based

How it works

Builds a binary search tree and traverses it.

Implementation

function treeSort(arr, stats) {
  const n = arr.length;
  function makeNode(val) {
    return {
      val: val,
      left: null,
      right: null
    };
  }
  let root = null;
  for (let i = 0; i < n; i++) {
    compare(i, i);
    let node = makeNode(arr[i]);
    if (!root) {
      root = node;
      continue;
    }
    let curr = root;
    while (true) {
      if (arr[i] < curr.val) {
        if (!curr.left) {
          curr.left = node;
          break;
        }
        curr = curr.left;
      } else {
        if (!curr.right) {
          curr.right = node;
          break;
        }
        curr = curr.right;
      }
    }
  }
  let i = 0;
  function traverse(node) {
    if (!node) return;
    traverse(node.left);
    arr[i] = node.val;
    write(i, node.val);
    markSorted(i);
    i++;
    traverse(node.right);
  }
  traverse(root);
}