selection sort


See On Github

Data

Source Code

--[[
	Author: Duc Thanh Tran (ducthanhtran, Github)
	Algorithm: Selectionsort, basic version where minimum element is searched for,
               not stable version!
	Date: 12/31/2013
--]]

local function selectionsort(T)
	assert(type(T) == "table", "Argument is not a table")

	local length = #T

	for i = 1, length-1 do
		local minElem = i

		for j = i+1, length do
			if T[j] < T[minElem] then
				minElem = j
			end
		end

		T[i], T[minElem] = T[minElem], T[i]
	end
end

return selectionsort
--[[
	Author: Duc Thanh Tran (ducthanhtran, Github)
	Algorithm: Selectionsort, basic version where minimum element is searched for,
               not stable version!
	Date: 12/31/2013
--]]

local selectionsort = require "selectionsort"

array = {-5, 3, 2, 0, 10, 6}

print("Unsorted list:")
print(table.concat(array, ", "))

selectionsort(array)

print("\nSorted list:")
print(table.concat(array, ", "))


assert(array[1] == -5, "Failed")
assert(array[2] == 0, "Failed")
assert(array[3] == 2, "Failed")
assert(array[4] == 3, "Failed")
assert(array[5] == 6, "Failed")
assert(array[6] == 10, "Failed")