So I am taking a computer science class on khan academy and am working on the algorithm part of the course. The most recent assignment was to sort a table and because I don't know java script well enough to program in it, I decided to write the code in Lua. Now I did not realize that khan academy wanted me to sort the table using a swap function I had created earlier. Here it is:
local testTable = {1, 2, 3} local function swap(tbl, indexOne, indexTwo) local secondIndexThingy = tbl[indexTwo] tbl[indexTwo] = tbl[indexOne] tbl[indexOne] = secondIndexThingy end swap(testTable, 1, 3)
So I went ahead and wrote this without the swap:
local numList = {3, 6, 4, 7, 9, 2, 5, 1, 8, 6} local function sortTableFromMinToMax(tbl) local sortedTable = {} for i = 1, #tbl do local smallestNumSoFar = false local indexOfSmallNum for index,v in pairs(tbl) do wait() if smallestNumSoFar then if v < smallestNumSoFar then smallestNumSoFar = v indexOfSmallNum = index end else smallestNumSoFar = v indexOfSmallNum = index end end table.insert(sortedTable, smallestNumSoFar) table.remove(tbl, indexOfSmallNum) end return sortedTable end
and it works. But I wanted to know. Is it better to do it the way khan academy had me doing it? Or is returning a whole new table rather than manipulating the old one more efficient?