Lua迭代式归并排序

-- 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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值