Bubblesort algorithm

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

4 Likes

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:

9 Likes

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 binary quick 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.

5 Likes

Remind me again what the difference between pairs and ipairs is?

1 Like

As I remember correctly pairs is used with dictionaries and ipairs is used with arrays

2 Likes

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)

link

I think it’s a quick sort actually!

Edit: it was mentioned here

3 Likes

I only implemented bubblesort beacuse it’s the easiest. If I needed to sort an array in the future I’d probably use table.sort.

1 Like

Yeah, if I had to sort something in an actual project I’d probably just use table.sort. But like you said, I enjoy knowing how things work.

idk what Blend_it said, but pairs goes, but if it reaches an error, it will stop, as opposed to ipairs which will recognize the error but keep going

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.

5 Likes