Search code examples
sortinglualuajit

How to get the ordering of an array in lua


Is there a (fast) way in lua to sort an array and also get the ordering, e.g.

a = {4,3.2,1,7}

=> ordering would be 3,2,1,4 (because a[3]=1, a[2]=3.2, ...)


Solution

  • Try the code below. It sorts an array of indices using the values for comparison.

    a = {4,3.2,1,7} 
    o = {}   
    for i=1,#a do
        o[i]=i
    end    
    table.sort(o,function (x,y) return a[x]<a[y] end)    
    for i=1,#o do
        print(i,o[i],a[o[i]])
    end