[modified] clean up source of stable_sort.lua

This commit is contained in:
Max Cahill 2020-03-10 13:14:26 +11:00
parent 94005675e9
commit 27b73543e0

View File

@ -103,21 +103,22 @@ function _sort_core.merge_sort_impl(array, workspace, low, high, less)
end end
end end
--inline common setup stuff function default_less(a, b)
function _sort_core.sort_setup(array, less)
local n = #array
local trivial = false
--trivial cases; empty or 1 element
if n <= 1 then
trivial = true
else
--default less
less = less or function (a, b)
return a < b return a < b
end end
--inline common setup stuff
function _sort_core.sort_setup(array, less)
--default less
less = less or default_less
--
local n = #array
--trivial cases; empty or 1 element
local trivial = (n <= 1)
if not trivial then
--check less --check less
if less(array[1], array[1]) then if less(array[1], array[1]) then
error("invalid order function for sorting") error("invalid order function for sorting; less(v, v) should not be true for any v.")
end end
end end
--setup complete --setup complete
@ -128,9 +129,10 @@ function _sort_core.stable_sort(array, less)
--setup --setup
local trivial, n, less = _sort_core.sort_setup(array, less) local trivial, n, less = _sort_core.sort_setup(array, less)
if not trivial then if not trivial then
--temp storage --temp storage; allocate ahead of time
local workspace = {} local workspace = {}
workspace[ math.floor( (n+1)/2 ) ] = array[1] local middle = math.ceil(n / 2)
workspace[middle] = array[1]
--dive in --dive in
_sort_core.merge_sort_impl( array, workspace, 1, n, less ) _sort_core.merge_sort_impl( array, workspace, 1, n, less )
end end