lua

Q: sorting a table of numbers in Lua


I've looked around for a bit to find a solution to my problem but I haven't gotten anything that completely fixes it. Essentially the function does sort but it doesn't sort the numbers in the table just the numbers 1 through 10

local numbers = {18, 45, 90, 77, 65, 18, 3, 57, 81, 10}

local function selectionSort(t)--t is the table to be sorted
 
  local t = {18, 45, 90, 77, 65, 18, 3, 57, 81, 10}
  
  local tkeys = {}
for k in pairs(t) do table.insert(tkeys, k) end
table.sort(tkeys)
for _, k in ipairs(tkeys) do print(k, t[k]) end
     
     
  return t -- return the sorted table
end

list = selectionSort(list)

and this is what comes out

1   18
2   45
3   90
4   77
5   65
6   18
7   3
8   57
9   81
10  10

and what I want is

3   18
10  45
18  90
18  77
45  65
57  18
65  3
77  57
81  81
90  10

any solutions?


Solution

  • You are taking the key from your input and you want the value.

    you can change it to:

    local list = {18, 45, 90, 77, 65, 18, 3, 57, 81, 10}
    
    local function selectionSort(t)--t is the table to be sorted
      
      local tSorted = {}
      for _,v in pairs(t) do 
        table.insert(tSorted, v)    
      end
      
      table.sort(tSorted)
      
      for i=1,#t,1 do 
        print(tSorted[i], t[i]) 
      end
      
      return tSorted -- return the sorted table
    end
    
    list = selectionSort(numbers)
    

    and you will get:

    sorted  original
    3       18
    10      45
    18      90
    18      77
    45      65
    57      18
    65      3
    77      57
    81      81
    90      10