Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this Lua DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.lua
local function merge_sort(values)
if #values <= 1 then return values end
local mid = math.floor(#values / 2)
local left, right = {}, {}
for i = 1, mid do left[#left + 1] = values[i] end
for i = mid + 1, #values do right[#right + 1] = values[i] end
left = merge_sort(left)
right = merge_sort(right)
local merged = {}
local i, j = 1, 1
while i <= #left and j <= #right do
if left[i] <= right[j] then merged[#merged + 1] = left[i]; i = i + 1
else merged[#merged + 1] = right[j]; j = j + 1 end
end
while i <= #left do merged[#merged + 1] = left[i]; i = i + 1 end
while j <= #right do merged[#merged + 1] = right[j]; j = j + 1 end
return merged
end
local arr = merge_sort({5, 1, 4, 2, 8})
io.write("[")
for k = 1, #arr do
if k > 1 then io.write(", ") end
io.write(tostring(arr[k]))
end
io.write("]\n")
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- Keep the explicit algorithmic steps instead of calling a standard-library sort. The replay is meant to expose comparisons, movement, and recursion.
- The implementation is intentionally compact for learning and replay, not a production sorting utility.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.