Skip to content

Instantly share code, notes, and snippets.

@balinterdi
Created July 12, 2019 17:22
Show Gist options
  • Save balinterdi/9587b86581069c16d50d56ef6e5bb0b0 to your computer and use it in GitHub Desktop.
Save balinterdi/9587b86581069c16d50d56ef6e5bb0b0 to your computer and use it in GitHub Desktop.
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