mirror of
https://github.com/1bardesign/batteries.git
synced 2024-11-25 23:24:35 +00:00
[modified] clean up source of stable_sort.lua
This commit is contained in:
parent
94005675e9
commit
27b73543e0
@ -103,21 +103,22 @@ function _sort_core.merge_sort_impl(array, workspace, low, high, less)
|
||||
end
|
||||
end
|
||||
|
||||
--inline common setup stuff
|
||||
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)
|
||||
function default_less(a, b)
|
||||
return a < b
|
||||
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
|
||||
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
|
||||
--setup complete
|
||||
@ -128,9 +129,10 @@ function _sort_core.stable_sort(array, less)
|
||||
--setup
|
||||
local trivial, n, less = _sort_core.sort_setup(array, less)
|
||||
if not trivial then
|
||||
--temp storage
|
||||
--temp storage; allocate ahead of time
|
||||
local workspace = {}
|
||||
workspace[ math.floor( (n+1)/2 ) ] = array[1]
|
||||
local middle = math.ceil(n / 2)
|
||||
workspace[middle] = array[1]
|
||||
--dive in
|
||||
_sort_core.merge_sort_impl( array, workspace, 1, n, less )
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user