-- region TestLua.lua
-- 2019.1.2
function Merge(list, leftIndex, midIndex, rightIndex)
local totalIndex = 1
local i = leftIndex
local j = midIndex + 1
local tempList = { }
while i <= midIndex or j <= rightIndex do
if (i > midIndex) then
tempList[totalIndex] = list[j]
j = j + 1
totalIndex = totalIndex + 1
elseif (j > rightIndex) then
tempList[totalIndex] = list[i]
i = i + 1
totalIndex = totalIndex + 1
else
if (list[i] <= list[j]) then
tempList[totalIndex] = list[i]
i = i + 1
totalIndex = totalIndex + 1
else
tempList[totalIndex] = list[j]
j = j + 1
totalIndex = totalIndex + 1
end
end
end
for k = 1, #tempList do
list[leftIndex] = tempList[k]
leftIndex = leftIndex + 1
end
end
function Sort(list)
-- step
local step = 1
while (step <= #list) do
-- offset
local offset = step * 2
local index = 1
while index <= #list do
Merge(list, index, math.min(index + step - 1, #list), math.min(index + offset - 1, #list))
index = index + offset
end
step = step * 2
end
end
--- <summary>
--- main logic.
--- </summary>
m_List = { 0, 40, 3, 20, 1 }
Sort(m_List)
--- <summary>
--- output string.
--- </summary>
m_Output = ""
for i, v in pairs(m_List) do
m_Output = m_Output .. tostring(v) .. ", "
end
print("m_Output=" .. m_Output)
os.execute("pause")
-- endregion
Lua迭代式归并排序
猜你喜欢
转载自blog.csdn.net/qq_37273889/article/details/85680659
今日推荐
周排行