SelectionSort not working

local Array = {6,10,2,2,4,50}

for i=1, #Array do
	MinValIndex = i 
	for j=(i+1), #Array do
		if Array[MinValIndex] > Array[j] then
			MinValIndex = Array[j]
		end
	end
	
	-- Swap the first element of the unsorted list with the lowest-value element
	Array[i], Array[MinValIndex] = Array[MinValIndex], Array[i]
end


print(Array)

However, the output I’m getting is totally incorrect and isn’t properly sorted at all.
image

Turns out it’s because MinValIndex = Array[j] should have been MinValIndex = j. As I was already getting the element j in the list through Array[MinValIndex]

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.