TSort
The TSort function sorts the values of 1 to 3 data collections into ascending order. If more than 1 collection is specified, the first one is used as the sorting key and the remaining collections are ordered according to the sorted key. The collection can be either a Lua array or a CImage.
Forms for sorting arrays (lua tables):
t1 = TSort( t1 )
key, t1 = TSort( key, t1 )
key, t1, t2 = TSort( key, t1, t2 )
key, t1, t2, t3 = TSort( key, t1, t2, t3 )
Forms for sorting elements of a CImage:
I1 = TSort( I1 )
CImageKey, I1 = TSort( CImageKey, I1 )
CImageKey, I1, I2 = TSort( CImageKey, I1, I2 )
CImageKey, I1, I2, I3 = TSort( CImageKey, I1, I2, I3 )
where
t1, t2, t3 are arrays (lua tables) to be sorted.
I1, I2, I3 are CImage objects to be sorted.
key is an array which serves as the sorting key.
CImageKey is a CImage object which serves as the sorting key.
On success, the modified tables or images are returned, otherwise nil is returned.
Arrays (Lua indexed tables) contain double precision real numbers, or data type "double". The CImage class supports data types ranging from byte to double. Numeric values other than double can be sorted faster by converting their array to a CImage. To sort into "reverse order", from largest to smallest, either use TSortR or follow TSort with TReverse on the table to be reversed, for example, as TReverse(TSort(t)).
The Lua table package contains a table.sort() function for sorting arrays of type table but it cannot be used with the CImage class. However, note that the TSort function can be much faster than the Lua library functiontable.sort(). For arrays having only about 100,000 or less points, the difference in speed usually is not noticed unless sorting is repeated inside an inner loop.
The following script sorts a table containing 1 million random numbers having values between 0 and 1. As always for a Lua, the numbers in the array have a data type of double. In a benchmark, TSort executed in 0.45 seconds while the Lua library package table.sort() required 1.86 seconds.
|
-- create a table with 1 million numbers |
|
-- sort the values |
The next script sorts the values in a CImage containing 1 million pixels of type ushort (16 bit unsigned integer). On the same computer, TSort required 0.227 seconds. Before running the script, the target image window was placed on top so that it would be attached by the script.
|
-- attach the topmost image window |
|
-- make sure an image window is on top |
|
-- sort the image |
The next script sorts 2 arrays, t1 and t2, using another array, k, as the sorting key:
|
-- setup the key table for sorting |
|
-- first table to be sorted by the key |
|
-- second table to be sorted by the key |
|
-- returns the sorted k, t1, t2 if successful |
|