问:在Lua中对数字表进行排序

SomeDude

我四处寻找可以解决我的问题的方法,但是我还没有得到完全解决它的方法。本质上,该函数可以对表进行排序,但它不对表中的数字进行排序,仅对数字1至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)

这就是结果

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

而我想要的是

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

有什么解决办法吗?

尼菲姆

您正在key从输入中获取,并且想要该值。

您可以将其更改为:

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)

您将获得:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章