Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/bench/tests/shootout/heapsort.lua
2727 views
1
--[[
2
MIT License
3
4
Copyright (c) 2017 Gabriel de Quadros Ligneul
5
6
Permission is hereby granted, free of charge, to any person obtaining a copy
7
of this software and associated documentation files (the "Software"), to deal
8
in the Software without restriction, including without limitation the rights
9
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
copies of the Software, and to permit persons to whom the Software is
11
furnished to do so, subject to the following conditions:
12
13
The above copyright notice and this permission notice shall be included in all
14
copies or substantial portions of the Software.
15
16
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
SOFTWARE.
23
]]
24
local function prequire(name) local success, result = pcall(require, name); return success and result end
25
local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../../bench_support")
26
27
function test()
28
29
30
local random, floor = math.random, math.floor
31
floor = math.ifloor or floor
32
33
function heapsort(n, ra)
34
local j, i, rra
35
local l = floor(n/2) + 1
36
-- local l = (n//2) + 1
37
local ir = n;
38
while 1 do
39
if l > 1 then
40
l = l - 1
41
rra = ra[l]
42
else
43
rra = ra[ir]
44
ra[ir] = ra[1]
45
ir = ir - 1
46
if (ir == 1) then
47
ra[1] = rra
48
return
49
end
50
end
51
i = l
52
j = l * 2
53
while j <= ir do
54
if (j < ir) and (ra[j] < ra[j+1]) then
55
j = j + 1
56
end
57
if rra < ra[j] then
58
ra[i] = ra[j]
59
i = j
60
j = j + i
61
else
62
j = ir + 1
63
end
64
end
65
ra[i] = rra
66
end
67
end
68
69
local Num = tonumber((arg and arg[1])) or 4
70
for i=1,Num do
71
local N = tonumber((arg and arg[2])) or 10000
72
local a = {}
73
for i=1,N do a[i] = random() end
74
heapsort(N, a)
75
for i=1,N-1 do assert(a[i] <= a[i+1]) end
76
end
77
78
end
79
80
bench.runCode(test, "heapsort")
81
82