forked from deutranium/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycleSort.lua
38 lines (37 loc) · 864 Bytes
/
cycleSort.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
--- Sort an array using cycle sort algorithm.
--- @param t table
--- @return table
local function cycleSort(t)
local n = #t
for i = 1, n do
local item = t[i]
local pos = i
for j = i + 1, n do
if t[j] < item then
pos = pos + 1
end
end
if pos == i then
goto continue
end
while item == t[pos] do
pos = pos + 1
end
t[pos], item = item, t[pos]
::continue::
while pos ~= i do
pos = i
for j = i + 1, n do
if t[j] < item then
pos = pos + 1
end
end
while item == t[pos] do
pos = pos + 1
end
t[pos], item = item, t[pos]
end
end
return t
end
return cycleSort