I decided make an array sorting algorithm in roblox because I’ve started to appreciate arrays way more It works by comparing pairs of values in the array and switching them depending on if they are smaller or bigger. I also decided to add some optimization in the form of a flag that will say if a value has been swapped or not, and if something hasn’t been swapped in the current iteration it’ll just break out of the loop.
Also, please tell me if I’m posting in the wrong category, and if I am I’m sorry about that.
local numbers = {5, 66, 1, 43, 97, 11}
for i = 1, #numbers do
local swapped = false
for e = 1, #numbers - 1 do
if numbers[e] < numbers[e + 1] then
local buffer = numbers[e]
numbers[e] = numbers[e + 1]
numbers[e + 1] = buffer
swapped = true
end
end
if not swapped then
break
end
end
for i, v in pairs(numbers) do
print(v)
end
This isn’t really a criticism of the code itself, but bubble sort is not the best table sorting algorithm. You can implement quick sort, or use table.sort which probably uses that internally anyways.
Also, minor nitpick, use ipairs rather than pairs (or a numeric for) for arrays:
Well, it works! You have it sorting in descending order though. That’s fine, but typically the default state of a sorter is ascending order. That can literally be toggled by switching around the < with > on your inner if statement.
As @rogchamp mentioned, Lua has a built-in table.sort method which uses a binaryquick sort, which is typically much faster. But I do appreciate the effort toward learning how to write a sorter from scratch. There’s a lot of value in understanding how those things work.
If it interests you, I have a topic explaining how one would make a quick sort, which is typically the sorting algorithm to go for and probably the faster with a complexity of O(n log n)
No, that is not the distinction. An error will stop both. ipairs just goes through the array portion of the table (with number indices, counting up from 1), while pairs goes through all of it.