-
Notifications
You must be signed in to change notification settings - Fork 98
/
mergeSort.lua
46 lines (45 loc) · 914 Bytes
/
mergeSort.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
39
40
41
42
43
44
45
46
--- Sort an array using the merge sort algorithm.
--- @param t table
--- @return table
local function mergeSort(t)
local n = #t
if n < 2 then
return t
end
local mid = math.floor(n / 2)
local left = {}
local right = {}
for i = 1, mid do
left[i] = t[i]
end
for i = mid + 1, n do
right[i - mid] = t[i]
end
left = mergeSort(left)
right = mergeSort(right)
local i = 1
local j = 1
local k = 1
while i <= #left and j <= #right do
if left[i] < right[j] then
t[k] = left[i]
i = i + 1
else
t[k] = right[j]
j = j + 1
end
k = k + 1
end
while i <= #left do
t[k] = left[i]
i = i + 1
k = k + 1
end
while j <= #right do
t[k] = right[j]
j = j + 1
k = k + 1
end
return t
end
return mergeSort