JavaScript Program to Implement Tree Sort

JavaScript Program to Implement Tree Sort

Tree Sort is a unique sorting algorithm that uses a Binary Search Tree (BST) to arrange data in order. The idea is simple: insert all elements of the array into a BST, and then perform an in-order traversal to retrieve the elements in sorted order. Since a BST stores smaller elements on the left and larger elements on the right, the in-order traversal naturally produces a sorted array.

Learning Tree Sort is important for beginners because it introduces the concept of using data structures to solve problems. Unlike other algorithms that rely purely on comparisons, Tree Sort combines sorting logic with tree structures, helping learners understand how trees can be used for practical applications like searching, inserting, and sorting. Tree Sort is used in applications where data is already partially structured or when implementing dynamic datasets.

Program 1: Basic Tree Sort

This program demonstrates a simple implementation of Tree Sort in JavaScript using a basic binary search tree.

class Node {

    constructor(value) {

        this.value = value;
        this.left = null;
        this.right = null;

    }

}

function insert(root, value) {

    if (root === null) {
        return new Node(value);
    }

    if (value < root.value) {
        root.left = insert(root.left, value);
    } else {
        root.right = insert(root.right, value);
    }

    return root;

}

function inOrderTraversal(root, result = []) {

    if (root !== null) {

        inOrderTraversal(root.left, result);
        result.push(root.value);
        inOrderTraversal(root.right, result);

    }

    return result;

}

function treeSort(arr) {

    let root = null;

    for (let i = 0; i < arr.length; i++) {
        root = insert(root, arr[i]);
    }

    return inOrderTraversal(root);

}

let numbers = [5, 3, 8, 1, 2, 7];

console.log("Sorted array:", treeSort(numbers));

This program works by first building a BST from the array and then performing an in-order traversal to get the sorted array. Beginners can think of it as “organizing numbers into a tree and reading them in order.” It is useful because it introduces the connection between data structures and algorithms.

Program 2: Tree Sort using recursion

This version focuses on recursion for both inserting nodes and traversing the tree, making the code cleaner and easier to understand.

class TreeNode {

    constructor(value) {

        this.value = value;
        this.left = null;
        this.right = null;

    }

}

function insertNode(root, value) {

    if (!root) return new TreeNode(value);

    root.left = value < root.value ? insertNode(root.left, value) : root.left;
    root.right = value >= root.value ? insertNode(root.right, value) : root.right;

    return root;

}

function traverseInOrder(root, result = []) {

    if (!root) return result;

    traverseInOrder(root.left, result);
    result.push(root.value);
    traverseInOrder(root.right, result);

    return result;

}

function treeSortRecursive(arr) {

    let root = null;

    arr.forEach(num => root = insertNode(root, num));
    return traverseInOrder(root);

}

let values = [12, 4, 5, 3, 8, 7];

console.log("Sorted array:", treeSortRecursive(values));

Here, both insertion and traversal are implemented recursively. Beginners can see how recursion simplifies tree operations, making it easier to manage left and right branches. This approach is widely used because it makes the code shorter and more readable.

Program 3: Tree Sort with descending order

This example shows how to modify Tree Sort to get the array in descending order by performing a reverse in-order traversal.

class TreeNode {

    constructor(value) {

        this.value = value;
        this.left = null;
        this.right = null;

    }

}

function insertNode(root, value) {

    if (!root) return new TreeNode(value);

    root.left = value < root.value ? insertNode(root.left, value) : root.left;
    root.right = value >= root.value ? insertNode(root.right, value) : root.right;

    return root;

}

function traverseInOrderDescending(root, result = []) {

    if (!root) return result;

    traverseInOrderDescending(root.right, result);

    result.push(root.value);

    traverseInOrderDescending(root.left, result);

    return result;

}

function treeSortDescending(arr) {

    let root = null;

    arr.forEach(num => root = insertNode(root, num));

    return traverseInOrderDescending(root);

}

let scores = [10, 5, 20, 15, 8];

console.log("Sorted array (descending):", treeSortDescending(scores));

By swapping the order of left and right traversal, the algorithm produces a descending sorted array. Beginners can understand this as simply reading the tree in the opposite order. It is useful when data ranking or reverse order is needed.

Program 4: Tree Sort handling duplicate values

This version demonstrates how Tree Sort naturally handles duplicate values without any extra logic.

class TreeNode {

    constructor(value) {

        this.value = value;
        this.left = null;
        this.right = null;

    }

}

function insertNode(root, value) {

    if (!root) return new TreeNode(value);

    root.left = value < root.value ? insertNode(root.left, value) : root.left;
    root.right = value >= root.value ? insertNode(root.right, value) : root.right;

    return root;

}

function traverseInOrder(root, result = []) {

    if (!root) return result;

    traverseInOrder(root.left, result);
    result.push(root.value);
    traverseInOrder(root.right, result);

    return result;

}

function treeSortRecursive(arr) {

    let root = null;

    arr.forEach(num => root = insertNode(root, num));
    return traverseInOrder(root);

}

let dataWithDuplicates = [7, 3, 7, 2, 8, 3, 5];

console.log("Sorted array with duplicates:", treeSortRecursive(dataWithDuplicates));

Tree Sort inserts duplicates into the right subtree. Beginners will see that duplicates are preserved, and the relative order among them is maintained during traversal. This makes Tree Sort stable in practice for repeated values.

Program 5: Tree Sort as a reusable function

This example wraps Tree Sort into a clean utility function that can be reused in multiple projects.

function treeSortUtility(arr) {

    class Node {

        constructor(value) {

            this.value = value;
            this.left = null;
            this.right = null;

        }

    }

    function insert(root, value) {

        if (!root) return new Node(value);

        if (value < root.value) root.left = insert(root.left, value);
        else root.right = insert(root.right, value);

        return root;

    }

    function inOrder(root, result = []) {

        if (!root) return result;

        inOrder(root.left, result);

        result.push(root.value);

        inOrder(root.right, result);

        return result;

    }

    let root = null;

    arr.forEach(num => root = insert(root, num));

    return inOrder(root);

}

let nums = [15, 10, 20, 8, 12, 17];

console.log("Sorted array:", treeSortUtility(nums));

This program highlights best practices for creating reusable functions. Beginners can easily integrate Tree Sort into other projects without rewriting the logic. It also demonstrates the power of combining data structures and sorting algorithms.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Tree Sort in JavaScript in simple terms.

Q1. What is Tree Sort in JavaScript?
Tree Sort is a sorting algorithm that builds a binary search tree from array elements and then retrieves them in sorted order using in-order traversal.

Q2. Can Tree Sort handle duplicates?
Yes, Tree Sort naturally handles duplicates by inserting them into the right subtree.

Q3. Is Tree Sort faster than Quick Sort or Merge Sort?
Tree Sort has average-case performance similar to Quick Sort (O(n log n)), but worst-case performance can be O(n²) if the tree becomes unbalanced.

Q4. Can Tree Sort sort in descending order?
Yes, performing a reverse in-order traversal of the tree produces a descending sorted array.

Q5. Why should beginners learn Tree Sort?
Tree Sort introduces the concept of using data structures for algorithms, helping beginners understand trees, recursion, and in-order traversal.

Conclusion

Tree Sort is a fascinating algorithm that combines sorting and tree data structures. It shows beginners how data structures like binary search trees can make sorting intuitive and practical.

Practicing Tree Sort helps learners understand recursion, tree traversal, and handling duplicates while strengthening algorithmic thinking in JavaScript. By experimenting with ascending and descending orders and different datasets, beginners can gain confidence in implementing tree-based algorithms and improve their programming skills.

Scroll to Top