Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/bench/tests/qsort.lua
2725 views
1
local function prequire(name) local success, result = pcall(require, name); return success and result end
2
local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support")
3
4
function test()
5
6
-- two implementations of a sort function
7
-- this is an example only. Lua has now a built-in function "sort"
8
9
-- extracted from Programming Pearls, page 110
10
function qsort(x,l,u,f)
11
if l<u then
12
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
13
x[l],x[m]=x[m],x[l] -- swap pivot to first position
14
local t=x[l] -- pivot value
15
m=l
16
local i=l+1
17
while i<=u do
18
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
19
if f(x[i],t) then
20
m=m+1
21
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
22
end
23
i=i+1
24
end
25
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
26
-- x[l+1..m-1] < x[m] <= x[m+1..u]
27
qsort(x,l,m-1,f)
28
qsort(x,m+1,u,f)
29
end
30
end
31
32
function selectionsort(x,n,f)
33
local i=1
34
while i<=n do
35
local m,j=i,i+1
36
while j<=n do
37
if f(x[j],x[m]) then m=j end
38
j=j+1
39
end
40
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
41
i=i+1
42
end
43
end
44
45
--function show(m,x)
46
-- io.write(m,"\n\t")
47
-- local i=1
48
-- while x[i] do
49
-- io.write(x[i])
50
-- i=i+1
51
-- if x[i] then io.write(",") end
52
-- end
53
-- io.write("\n")
54
--end
55
56
function testsorts(x)
57
local n=1
58
while x[n] do n=n+1 end; n=n-1 -- count elements
59
--show("original",x)
60
qsort(x,1,n,function (x,y) return x<y end)
61
--show("after quicksort",x)
62
selectionsort(x,n,function (x,y) return x>y end)
63
--show("after reverse selection sort",x)
64
qsort(x,1,n,function (x,y) return x<y end)
65
--show("after quicksort again",x)
66
end
67
68
-- array to be sorted
69
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
70
71
local ts0 = os.clock()
72
for loops=1,10000 do
73
testsorts(x)
74
end
75
local ts1 = os.clock()
76
77
return ts1 - ts0
78
end
79
80
bench.runCode(test, "qsort")
81