-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathcocktailSort.lua
More file actions
33 lines (32 loc) · 780 Bytes
/
cocktailSort.lua
File metadata and controls
33 lines (32 loc) · 780 Bytes
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
--- Sort an array using the cocktail sort algorithm.
--- @param t table
--- @return table
local function cocktailSort(t)
local n = #t
local swapped = true
local start = 1
local end_ = n - 1
while swapped do
swapped = false
for i = start, end_ do
if t[i] > t[i + 1] then
t[i], t[i + 1] = t[i + 1], t[i]
swapped = true
end
end
if not swapped then
break
end
swapped = false
end_ = end_ - 1
for i = end_, start, -1 do
if t[i] < t[i - 1] then
t[i], t[i - 1] = t[i - 1], t[i]
swapped = true
end
end
start = start + 1
end
return t
end
return cocktailSort