Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A highly efficient bubble sort algorithm in Lua
function print_array(a)
local i = 1
while a[i] do
print(a[i])
i = i + 1
end
end
function bubblesort(t)
local swapsMade;
repeat
swapsMade = false
for i=1,#t-1 do
-- print(t[i] .. " " .. t[i+1])
local a, b = t[i], t[i+1]
if a > b then
t[i], t[i+1] = b, a
swapsMade = true
end
end
-- break if no swaps were made
until swapsMade == false
return t;
end
local a = { 8, -3, 9, 4, 24, 2, -100, 12, 1 }
local sorted = bubblesort(a)
print_array(sorted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.