Last active
February 29, 2020 07:33
-
-
Save zambony/92096b990c5822dd89218575ef29baf5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Convenience function to explode some text | |
local function explode(str, separator) | |
local out = {} | |
for w in str:gmatch("([^" .. separator .. "]+)") do out[#out + 1] = w end | |
return out | |
end | |
local defaultComp = function(a, b) return a > b end | |
local function mergeHelper(t, p, q, r, comp) | |
local leftSize = q - p + 1 | |
local rightSize = r - q | |
local left = {} | |
local right = {} | |
for i = 1, leftSize do | |
left[i] = t[p + i - 1] | |
end | |
for i = 1, rightSize do | |
right[i] = t[q + i] | |
end | |
local i = 1 | |
local j = 1 | |
for k = p, r do | |
if (comp(left[i], right[j])) then | |
t[k] = left[i] | |
i = i + 1 | |
else | |
t[k] = right[j] | |
j = j + 1 | |
end | |
end | |
end | |
--[[ | |
Args: | |
t - table to sort | |
p - starting index | |
r - ending index | |
comp - optional comparison function for custom sorting | |
--]] | |
function table.mergesort(t, p, r, comp) | |
comp = comp or defaultComp | |
if (p < r) then | |
local q = math.floor((p + r) / 2) | |
table.mergesort(t, p, q, comp) | |
table.mergesort(t, q + 1, r, comp) | |
mergeHelper(t, p, q, r, comp) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment