Quick actions

cmd+k|ctrl+k

Navigation

Languages

Bubblesort

Snippet info

Language

Lua

Visibility

public

Author

captain.g

Created

2021-02-18T02:46:16Z

Updated

2021-02-18T04:34:50Z

-- Bubble sort algorithm
-- https://www.geeksforgeeks.org/bubble-sort/

local function bubblesort(t)
    local length = #t
    -- Tell if a should come before b
    -- The <= to handle equal values

    for pass = 1, math.huge do
        local swapped  -- a bool to determine if we swapped this pass

        for i = 1, length - 1 do
            local a = t[i]
            -- The next value, b
            local b = t[i + 1]
            -- Tell if a should come after b
            -- Swap if it didn't pass the order check
            if a > b then
                t[i + 1] = a
                t[i] = b
                swapped = true
            end
        end

        -- Everything is sorted when there are no swaps in this pass
        if not swapped then
            break
        end
    end
end

local function randomt(size, range)
    local t = {}
    for i = 1, size do
        t[i] = math.random(1, range)
    end
    return t
end
local t = randomt(1000, 100)
--print(table.concat(t,", "))
local start = os.clock()
bubblesort(t)
print(os.clock() - start)

-- on average, 0.1 - 0.15s for a array of size 1000
--print(table.concat(t,", "))
INFO