1 -- two implementations of a sort function
2 -- this is an example only. Lua has now a built-in function "sort"
4 -- extracted from Programming Pearls, page 110
5 function qsort(x,l,u,f)
7 local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
8 x[l],x[m]=x[m],x[l] -- swap pivot to first position
9 local t=x[l] -- pivot value
13 -- invariant: x[l+1..m] < t <= x[m+1..i-1]
16 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
20 x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
21 -- x[l+1..m-1] < x[m] <= x[m+1..u]
27 function selectionsort(x,n,f)
32 if f(x[j],x[m]) then m=j end
35 x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
46 if x[i] then io.write(",") end
53 while x[n] do n=n+1 end; n=n-1 -- count elements
55 qsort(x,1,n,function (x,y) return x<y end)
56 show("after quicksort",x)
57 selectionsort(x,n,function (x,y) return x>y end)
58 show("after reverse selection sort",x)
59 qsort(x,1,n,function (x,y) return x<y end)
60 show("after quicksort again",x)
64 x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}