Lua Program to Implement Tree Sort

Lua Program to Implement Tree Sort

Tree Sort is a sorting algorithm that uses a special data structure called a Binary Search Tree (BST) to organize data. Unlike simple sorting methods like Bubble Sort or Insertion Sort, Tree Sort first inserts all elements into a tree in such a way that smaller elements go to the left and larger elements go to the right. Then, it reads the elements in order by traversing the tree, resulting in a sorted list. This approach is efficient and helps beginners understand how data structures like trees can make sorting more powerful.

Tree Sort is important because it combines the concepts of data structures and sorting into one algorithm. It is often used when you want to maintain dynamic data, like keeping a set of numbers sorted while adding new numbers frequently. Learning Tree Sort in Lua also helps beginners practice recursion, which is a fundamental concept in programming. By the end of this article, you will have a clear understanding of Tree Sort and several practical ways to implement it in Lua.

Program 1: Basic Tree Sort using recursion

This first program demonstrates a simple implementation of Tree Sort using a Binary Search Tree built with recursion. It works well for positive integers.

-- Basic Tree Sort in Lua

-- Node structure
function newNode(data)
    return {value = data, left = nil, right = nil}
end

-- Insert a value into the BST
function insert(root, data)

    if root == nil then
        return newNode(data)
    end

    if data < root.value then
        root.left = insert(root.left, data)
    else
        root.right = insert(root.right, data)
    end

    return root

end

-- Inorder traversal to get sorted array
function inorder(root, arr)

    if root ~= nil then

        inorder(root.left, arr)

        table.insert(arr, root.value)

        inorder(root.right, arr)

    end

end

function treeSort(arr)

    local root = nil

    for i = 1, #arr do
        root = insert(root, arr[i])
    end

    local sorted = {}

    inorder(root, sorted)

    return sorted

end

local numbers = {5, 3, 8, 1, 4, 7}
local sortedNumbers = treeSort(numbers)

for _, v in ipairs(sortedNumbers) do
    io.write(v .. " ")
end

This program works by first building a tree with the input values. The inorder traversal then reads the tree from smallest to largest, producing a sorted list. Beginners can see how recursion naturally handles both insertion and traversal, making the code elegant and simple.

Program 2: Tree Sort with clearer comments

In this version, comments are added to explain each step. The logic remains the same but it’s easier to follow for beginners.

-- Tree Sort with detailed comments

-- Create a new tree node
function newNode(data)
    return {value = data, left = nil, right = nil}
end

-- Insert a node into the tree
function insert(root, data)

    if root == nil then
        return newNode(data)
    end

    if data < root.value then
        root.left = insert(root.left, data)
    else
        root.right = insert(root.right, data)
    end

    return root

end

-- Inorder traversal collects sorted elements
function inorder(root, arr)

    if root ~= nil then

        inorder(root.left, arr)

        table.insert(arr, root.value)

        inorder(root.right, arr)

    end

end

-- Main Tree Sort function
function treeSort(arr)

    local root = nil

    for i = 1, #arr do
        root = insert(root, arr[i])
    end

    local sorted = {}

    inorder(root, sorted)

    return sorted

end

local data = {10, 2, 8, 6, 4, 12}
local sortedData = treeSort(data)

for _, v in ipairs(sortedData) do
    print(v)
end

This version helps beginners understand that Tree Sort consists of two main parts: building the tree and traversing it. Each function is explained clearly, which makes learning recursion easier.

Program 3: Tree Sort with step-by-step printing

This program prints the tree traversal steps to show how the array is being sorted.

-- Tree Sort with step output

function newNode(data)
    return {value = data, left = nil, right = nil}
end

function insert(root, data)

    if root == nil then
        return newNode(data)
    end

    if data < root.value then
        root.left = insert(root.left, data)
    else
        root.right = insert(root.right, data)
    end

    return root

end

function inorder(root, arr)

    if root ~= nil then

        inorder(root.left, arr)

        table.insert(arr, root.value)
        print("Added " .. root.value .. " to sorted array")

        inorder(root.right, arr)

    end

end

function treeSort(arr)

    local root = nil

    for i = 1, #arr do
        root = insert(root, arr[i])
    end

    local sorted = {}

    inorder(root, sorted)

    return sorted

end

local sample = {7, 4, 9, 1, 6}
local sortedSample = treeSort(sample)

for _, v in ipairs(sortedSample) do
    io.write(v .. " ")
end

Printing the steps helps beginners visualize the recursion. You can see exactly how values are added in order, which makes understanding Tree Sort more tangible.

Program 4: Reusable Tree Sort function

This version wraps Tree Sort as a reusable function suitable for larger projects or libraries.

-- Reusable Tree Sort utility

function treeSort(arr)

    local function newNode(data)
        return {value = data, left = nil, right = nil}
    end

    local function insert(root, data)

        if root == nil then return newNode(data) end

        if data < root.value then
            root.left = insert(root.left, data)
        else
            root.right = insert(root.right, data)
        end

        return root

    end

    local function inorder(root, sorted)

        if root ~= nil then

            inorder(root.left, sorted)

            table.insert(sorted, root.value)

            inorder(root.right, sorted)

        end

    end

    local root = nil

    for _, v in ipairs(arr) do
        root = insert(root, v)
    end

    local sorted = {}
    inorder(root, sorted)
    return sorted

end

local numbers = {15, 10, 20, 8, 12, 18}
local sortedNumbers = treeSort(numbers)

for _, v in ipairs(sortedNumbers) do
    io.write(v .. " ")
end

This version is practical for real-world Lua projects. Beginners learn how to package code neatly and reuse it, which is an essential programming skill.

Program 5: Tree Sort supporting negative and floating-point numbers

Tree Sort naturally handles negative and decimal numbers because it relies on comparisons, not counting or indices. This program demonstrates that.

-- Tree Sort with negative and floating-point numbers

function newNode(data)
    return {value = data, left = nil, right = nil}
end

function insert(root, data)

    if root == nil then return newNode(data) end

    if data < root.value then
        root.left = insert(root.left, data)
    else
        root.right = insert(root.right, data)
    end

    return root

end

function inorder(root, arr)

    if root ~= nil then

        inorder(root.left, arr)

        table.insert(arr, root.value)

        inorder(root.right, arr)

    end

end

function treeSort(arr)

    local root = nil

    for _, v in ipairs(arr) do
        root = insert(root, v)
    end

    local sorted = {}

    inorder(root, sorted)

    return sorted

end

local mixed = {3.5, -2, 4.1, 0, -1.7, 2}
local sortedMixed = treeSort(mixed)

for _, v in ipairs(sortedMixed) do
    io.write(v .. " ")
end

This program shows that Tree Sort is versatile. Beginners can apply it to any numeric data without additional tweaks, unlike algorithms that rely on array indices.

Frequently Asked Questions (FAQ)

Here are common questions beginners have about Tree Sort in Lua.

Q1. Is Tree Sort stable?
No, Tree Sort is not stable by default because inserting equal elements may not preserve their original order.

Q2. Can Tree Sort handle negative numbers?
Yes, Tree Sort works naturally with negative numbers and floating-point numbers since it only uses comparisons.

Q3. Is Tree Sort faster than Quick Sort?
Tree Sort has average performance similar to Quick Sort, but its worst-case time can be slower if the tree is unbalanced.

Q4. Why use Tree Sort instead of simpler sorts?
Tree Sort is useful when you want to maintain dynamic data in a sorted order, allowing fast insertions and retrievals.

Q5. Do I need recursion for Tree Sort?
Recursion makes Tree Sort easier to implement, but you can also use iterative approaches with stacks if preferred.

Conclusion

Tree Sort is a powerful algorithm that combines sorting with tree-based data structures. In this article, you explored multiple ways to implement Tree Sort in Lua, including basic recursion, step-by-step tracing, reusable functions, and handling negative and floating-point numbers. Each version was designed to help beginners understand the core concepts clearly.

By practicing these examples, experimenting with your own datasets, and visualizing how the tree organizes data, you can strengthen both your Lua programming skills and your understanding of recursion and data structures. Tree Sort shows that learning data structures alongside sorting algorithms creates a deeper appreciation for how efficient programming works.

Scroll to Top