0 Replies - 289 Views - Last Post: 08 April 2009 - 07:32 PM

#1 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,235
  • Joined: 14-September 07

[LUA]Lua: BubbleSort

Posted 08 April 2009 - 07:32 PM

Description: Implement to sort data. Bubble sorts a table (assuming it has comparable numerical values) in Lua.
--KYA 4/8/09 Lua
--sort a table passed to the function
function bubbleSort(table)
--check to make sure the table has some items in it
	if #table < 2 then
		print("Table does not have enough data in it")
		return
	end

	for i = 1, #table do --> array start to end
		for j = 2, #table do
			if table[j] < table[j-1] then -->switch
				temp = table[j-1]
				table[j-1] = table[j]
				table[j] = temp
			end
		end
	end

	return
end

--example usage
table = {1,10,5,6,7}
for i = 1, #table do
     print(table[i])
end
bubbleSort(table)
print("n")
for i = 1, #table do
     print(table[i])
end



Is This A Good Question/Topic? 0
  • +

Page 1 of 1