Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

[Solved]Which method is better when sorting a table?

Asked by 5 years ago
Edited 5 years ago

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?

0
This is a class on algorithms. I know that there is table.sort but that is not the point. User#21908 42 — 5y
0
The name of the algorithm I was supposed to do was: selection algorithm. User#21908 42 — 5y
0
Which sorting method is this? Bubble Sort maybe... benben3963 6 — 5y
0
Or is it Quicksort... benben3963 6 — 5y
0
idk User#21908 42 — 5y

Answer this question