I'm curious what algorithm Lua's default table.sort
uses, only because it's slower than some other sorting algorithms I've come across. I'm also curious if Lua's table.sort
is written in the Engine in C, or if it's in a library in Lua.
Asked
Active
Viewed 3,104 times
5

hjpotter92
- 78,589
- 36
- 144
- 183

jocopa3
- 796
- 1
- 10
- 29
2 Answers
6
What algorithm does table.sort use?
The comment in tablib.c
(scroll up a bit) states
/*
** {======================================================
** Quicksort
** (based on `Algorithms in MODULA-3', Robert Sedgewick;
** Addison-Wesley, 1993.)
** =======================================================
*/
You can read the source code at the link I provided.
I'm also curious if Lua's table.sort is written in the Engine in C, or if it's in a library in Lua.
At this time, all libraries that come directly with Lua (io
, table
, math
, ...) are written in C.
-
Note that LuaJIT is considering switching to [smoothsort](http://en.wikipedia.org/wiki/Smoothsort), and several of its library functions are now implemented in Lua bytecode (which is actually beneficial because it can then be JIT compiled better) – Colonel Thirty Two Aug 06 '13 at 02:59
3
Internally, table.sort
uses quicksort, and it's written in C. Note that quicksort is not stable. And a little bit surprisingly to me, Lua didn't use C's qsort()
directly.
As to performance, it's hard to tell since there are various factors, for example, what language and what algorithm you are comparing with, and what kind of data is being tested.

Yu Hao
- 119,891
- 44
- 235
- 294
-
Using Lua, there are a couple algorithms I found that are a bit faster than the default. If size relevantly small, cocktail sort and bubble sort are actually faster than the default. If the size is large, then LSD Radix sort, along with the other two I said, are faster. I am testing it with different types of data, such as reversed arrays, random arrays and even mostly sorted arrays, but for each test, default sort is still a bit slower. – jocopa3 Aug 04 '13 at 14:32
-
2@jocopa3 As far as I see, this is not Lua's problem, rather quicksort's. e.g, quicksort performs poorly on sorted arrays and reversed arrays. If you need to do sorting on specific problems, and Lua's default sort doesn't work well enough, then maybe writing a specific sort algorithm in C yourself is a good idea. – Yu Hao Aug 04 '13 at 14:38
-
@YuHao From looking at the linked source, Lua's qsort is choosing middle as the pivot everytime. That should be close to qsort's ideal case and it shouldn't be performing poorly. I suspect all those lua API calls might be what's slowing things down but can't be sure unless it's profiled. – greatwolf Aug 04 '13 at 22:48
-
@greatwolf The OP said in the comment that he is using Lua as comparison, so your suspect seems reasonable, but I'm not sure either, unless it's profiled. – Yu Hao Aug 05 '13 at 02:07