|
2013/5/8 Eike Decker <zet23t@googlemail.com>:
And wrong.
>> I only wrote this quickly and haven't given it intensive testing, but this
>> sort function is pretty simple, short, stable and fast
Say on the first iteration you take the "else" branch. It stores `vb`
local pos = a
while a <= e1 and b <= e2 do
local va,vb = arr[a], arr[b]
if a <= e1 and fn(va,vb) then
arr[pos] = va
a = a + 1
else
arr[pos] = vb
b = b + 1
end
pos = pos + 1
end
in `arr[pos]` which is `arr[a]`. So `arr[a]` is now clobbered. It
still sits in `va` but `va` is not used again.
You can postpone the inevitable by:
local pos, va, vb = a, arr[a], arr[b]
while a <= e1 and b <= e2 do
if a <= e1 and fn(va,vb) thenva = arr[a]
arr[pos] = va
a = a + 1
elsevb = arr[b]
arr[pos] = vb
b = b + 1
endNow you need to take the "else" branch twice in a row before
pos = pos + 1
end
something goes wrong.
There are in-place merge sorts around but they are not this simple.