# Omnimaga

## Calculator Community => TI Calculators => Lua => Topic started by: pianoman on July 15, 2011, 01:01:23 pm

Title: Sorting tables
Post by: pianoman on July 15, 2011, 01:01:23 pm
Hi again!
Just wondering, how do you use the sort feature in Lua for tables?
Thank you very much!
Title: Re: Sorting tables
Post by: Munchor on July 15, 2011, 01:05:53 pm
Code: [Select]
`> mytable = {"omnimaga", "pianoman", "ephan"}> -- When order alphabetically, it should be "ephan", "omnimaga", "pianoman"> table.sort(mytable)> = a[1]ephan> = a[2]omnimaga> = a[3]pianoman`
table.sort() sorts a table of strings alphabetically or numerically, if it is table of integers:

Code: [Select]
`> myinttable = {4,2,1,3}> table.sort(myinttable)> return  myinttable[1]1> return  myinttable[2]2> return  myinttable[3]3> return  myinttable[4]4`
Title: Re: Sorting tables
Post by: pianoman on July 15, 2011, 01:08:27 pm
Interesting... could be very useful.
Thanks, ephan!
Title: Re: Sorting tables
Post by: Jim Bauwens on July 15, 2011, 01:12:18 pm
This is a direct quote from http://lua-users.org/wiki/TableLibraryTutorial , which I describes the usage very good:
Quote
table.sort(table [, comp])

Sort the elements of a table in-place (i.e. alter the table).
Code: (Lua) [Select]
`> t = { 3,2,5,1,4 }> table.sort(t)> = table.concat(t, ", ")  -- display sorted values1, 2, 3, 4, 5`
If the table has a specified size only the range specified is sorted, e.g.,
Code: (Lua) [Select]
`> t = { 3,2,5,1,4; n=3 }   -- construct a table with user size of 3> table.sort(t)            -- sort will be limited by user size> = table.concat(t, ", ")  -- only specified size is concatenated as well2, 3, 5`
A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence. The default behaviour is for the < comparison to be made. For example, the following behaves the same as no function being supplied:

Code: (Lua) [Select]
`> t = { 3,2,5,1,4 }> table.sort(t, function(a,b) return a<b end)> = table.concat(t, ", ")1, 2, 3, 4, 5        `We can see if we reverse the comparison the sequence order is reversed.

Code: (Lua) [Select]
`> table.sort(t, function(a,b) return a>b end)> = table.concat(t, ", ")5, 4, 3, 2, 1`

Edit: Ephan's post is also very informative
Title: Re: Sorting tables
Post by: Munchor on July 15, 2011, 01:14:06 pm
Interesting... could be very useful.
Thanks, ephan!

The typical example is the classic program when the user will enter N numbers and you have to sort them and print them out. I just coded this:

Code: [Select]
`n = io.read()n = tonumber(n)f = {}for i=1,n do    a = io.read()    table.insert(f, a)endtable.sort(f)print("")for i=1,n do    print(f[i])end`
This gets a variable N as input from the user, then it reads N numbers. After this, it prints them ordered.