Lua Program to Implement Bubble Sort

Lua Program to Implement Bubble Sort

Bubble Sort is one of the simplest sorting algorithms you can learn as a beginner. The idea is very old and traditional, and that is what makes it special. It works by comparing two nearby values and swapping them if they are in the wrong order. This process repeats again and again until everything is sorted. Because the logic is simple and easy to follow, Bubble Sort is often the first sorting algorithm taught to new programmers.

Even though Bubble Sort is not the fastest algorithm, it still matters. It helps beginners understand how sorting works behind the scenes, instead of relying on built-in magic. In Lua programming, Bubble Sort is a great way to practice loops, conditions, tables, and basic logic. You may see similar ideas used in simple games, small tools, or learning projects where performance is not the main concern.

Program 1: Basic Bubble Sort Using Nested Loops

This program shows the most classic way to implement Bubble Sort in Lua. It uses two loops to repeatedly compare and swap values in a table. This is the version most beginners start with.

local numbers = {64, 34, 25, 12, 22, 11, 90}

for i = 1, #numbers do

    for j = 1, #numbers - i do

        if numbers[j] > numbers[j + 1] then
            numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
        end

    end

end

for i = 1, #numbers do
    print(numbers[i])
end

This code works by pushing the largest value to the end during each pass. The inner loop does the comparison and swapping, while the outer loop repeats the process until the table is sorted. Beginners can understand this easily because every step is visible and logical.

Program 2: Bubble Sort with Early Exit Optimization

This version improves the basic Bubble Sort by stopping early if no swaps happen. It saves time when the table is already sorted or almost sorted.

local numbers = {5, 1, 4, 2, 8}
local swapped = true

while swapped do

    swapped = false

    for i = 1, #numbers - 1 do

        if numbers[i] > numbers[i + 1] then

            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
            swapped = true

        end

    end

end

for i = 1, #numbers do
    print(numbers[i])
end

The idea here is simple. If a full pass happens without any swap, the table must already be sorted. This teaches beginners how small checks can make programs smarter and more efficient without changing the core logic.

Program 3: Bubble Sort in Descending Order

Sometimes you want values sorted from biggest to smallest. This program tweaks Bubble Sort to do exactly that.

local numbers = {3, 7, 1, 9, 2}

for i = 1, #numbers do

    for j = 1, #numbers - i do

        if numbers[j] < numbers[j + 1] then
            numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
        end

    end

end

for i = 1, #numbers do
    print(numbers[i])
end

The only change is the comparison sign. This shows beginners how flexible Bubble Sort is and how small logic changes can give different results. It is useful when ranking scores or sorting values in reverse order.

Program 4: Bubble Sort Using a While Loop Only

This program avoids nested for loops and uses while loops instead. It shows that Bubble Sort can be written in different styles.

local numbers = {10, 9, 8, 7, 6}
local n = #numbers
local i = 1

while i <= n do

    local j = 1

    while j <= n - i do

        if numbers[j] > numbers[j + 1] then
            numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
        end

        j = j + 1

    end

    i = i + 1

end

for k = 1, #numbers do
    print(numbers[k])
end

This approach helps beginners understand loop control better. It also proves that algorithms are about ideas, not just one fixed syntax. Learning different loop styles builds confidence in Lua programming.

Program 5: Recursive Bubble Sort in Lua

This version uses recursion instead of loops. It is more advanced but still good for learning.

local numbers = {4, 3, 2, 1}

local function bubbleSort(arr, n)

    if n == 1 then
        return
    end

    for i = 1, n - 1 do

        if arr[i] > arr[i + 1] then
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
        end

    end

    bubbleSort(arr, n - 1)

end

bubbleSort(numbers, #numbers)

for i = 1, #numbers do
    print(numbers[i])
end

Recursive Bubble Sort shows how a problem can be broken into smaller parts. Beginners learn how functions can call themselves and slowly reach a solution. This style is helpful for understanding recursion in Lua.

Program 6: Bubble Sort for String Values

Bubble Sort is not limited to numbers. This program sorts words alphabetically.

local words = {"lua", "python", "c", "java", "ruby"}

for i = 1, #words do

    for j = 1, #words - i do

        if words[j] > words[j + 1] then
            words[j], words[j + 1] = words[j + 1], words[j]
        end

    end

end

for i = 1, #words do
    print(words[i])
end

Lua can compare strings directly, so Bubble Sort works without extra effort. This is useful when sorting names, commands, or simple text data. Beginners can see that the same algorithm works for different data types.

Program 7: Bubble Sort with Step-by-Step Output

This version prints the table after each pass to show how Bubble Sort works internally.

local numbers = {5, 4, 3, 2, 1}

for i = 1, #numbers do

    for j = 1, #numbers - i do

        if numbers[j] > numbers[j + 1] then
            numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
        end

    end

    for k = 1, #numbers do
        io.write(numbers[k] .. " ")
    end

    print()

end

Seeing each step makes learning easier. Beginners can clearly watch values move into place. This traditional teaching style is great for understanding how Bubble Sort slowly improves the order.

Program 8: Bubble Sort Inside a Reusable Function

Here Bubble Sort is wrapped inside a function so it can be reused.

local function bubbleSort(arr)

    for i = 1, #arr do

        for j = 1, #arr - i do

            if arr[j] > arr[j + 1] then
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
            end

        end

    end

end

local numbers = {8, 3, 6, 2, 7}
bubbleSort(numbers)

for i = 1, #numbers do
    print(numbers[i])
end

This approach teaches clean coding habits. Beginners learn how to separate logic from data and reuse code. This is a very important habit in real Lua projects.

Program 9: Bubble Sort Handling Negative and Floating Point Numbers

Bubble Sort already supports negative and floating point numbers, but this program clearly demonstrates that behavior.

local numbers = {3.5, -2.1, 4.8, 0, -7.3}

for i = 1, #numbers do

    for j = 1, #numbers - i do

        if numbers[j] > numbers[j + 1] then
            numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
        end

    end

end

for i = 1, #numbers do
    print(numbers[i])
end

Lua compares numbers naturally, so no extra logic is needed. This reassures beginners that Bubble Sort works for real-world numeric data, including decimals and negative values.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Bubble Sort in Lua.

Q1. Is Bubble Sort good for large data sets?
Bubble Sort is easy to understand but slow for large data. It is best used for learning or very small tables.

Q2. Does Lua have a built-in sort function?
Yes, Lua provides table.sort, but learning Bubble Sort helps you understand how sorting really works.

Q3. Can Bubble Sort handle duplicate values?
Yes, duplicate values are handled naturally and stay grouped together after sorting.

Q4. Why is Bubble Sort still taught today?
It teaches core programming ideas like loops, comparisons, and swapping in a very clear way.

Conclusion

Bubble Sort is a simple and traditional sorting algorithm that every beginner should learn. In this article, you saw many Lua programs that implement Bubble Sort using different styles like loops, recursion, and functions. You also learned that it works with numbers, text, negative values, and floating point data.

The best way to master Bubble Sort in Lua is to practice and experiment. Try changing the data, reversing the order, or printing extra steps. Once you are comfortable, learning faster algorithms will feel much easier. Keep coding, stay curious, and enjoy the journey.

Scroll to Top