Lua递归式归并排序

-- region TestLua.lua
-- 2019.1.2

m_TempTuple = { }

--- <summary>
--- Merge(tuple, leftIndex, rightIndex, midIndex, tempTuple)
--- merge all elements between left index and right index. (contains mode)
--- the left array is tuple[leftIndex, midIndex]
--- the right array is tuple[midIndex + 1, rightIndex]
--- </summary>
function Merge(tuple, leftIndex, rightIndex, midIndex, tempTuple)
--    print("Merge", "leftIndex=" .. tostring(leftIndex), "rightIndex=" .. tostring(rightIndex), "midIndex=" .. tostring(midIndex))
    local totalIndex = 1

    -- left start index
    local i = leftIndex;

    -- right start index
    local j = midIndex + 1;

    -- copy elements from tuple to temp tuple in order.
    -- util one of parts is empty among left and right part.
    while (i <= midIndex and j <= rightIndex) do
        if (tuple[i] <= tuple[j])
        then
            tempTuple[totalIndex] = tuple[i]
            totalIndex = totalIndex + 1
            i = i + 1
        else
            tempTuple[totalIndex] = tuple[j]
            totalIndex = totalIndex + 1
            j = j + 1
        end
    end

    -- the remain elements are larger than any element in temp tuple.
    -- so copy all remian elements to temp tuple.
    -- left
    while (i <= midIndex) do
        tempTuple[totalIndex] = tuple[i]
        i = i + 1
        totalIndex = totalIndex + 1
    end

    -- right
    while (j <= rightIndex) do
        tempTuple[totalIndex] = tuple[j]
        j = j + 1
        totalIndex = totalIndex + 1
    end

    -- copy all elements in temp tuple to tuple.
    totalIndex = 1
    while (leftIndex <= rightIndex) do
--        print("after merge", "leftIndex=" .. tostring(leftIndex), "rightIndex=" .. tostring(rightIndex))
        tuple[leftIndex] = tempTuple[totalIndex]
        leftIndex = leftIndex + 1
        totalIndex = totalIndex + 1
    end
end

--- <summary>
--- Sort(tuple, leftIndex, rightIndex, tempTuple)
--- sort elements in tuple[leftIndex, rightIndex]
--- tempTuple : store elements sorted.
--- </summary>
function Sort(tuple, leftIndex, rightIndex, tempTuple)
--    print("Sort", "leftIndex=" .. tostring(leftIndex), "rightIndex=" .. tostring(rightIndex))
    if (leftIndex < rightIndex)
    then
        local midIndex = math.floor((leftIndex + rightIndex) / 2)

        -- sort left parts.
        Sort(tuple, leftIndex, midIndex, tempTuple)

        -- sort right parts.
        Sort(tuple, midIndex + 1, rightIndex, tempTuple)

        -- merge left and right parts.
        Merge(tuple, leftIndex, rightIndex, midIndex, tempTuple)
    end
end

--- <summary>
--- main logic.
--- </summary>
m_Tuple = { 5, 14, 30, 20, 100 }
Sort(m_Tuple, 1, #m_Tuple, m_TempTuple)

--- <summary>
--- output string.
--- </summary>
m_Output = ""
for i, v in pairs(m_Tuple) do
    m_Output = m_Output .. tostring(v) .. ", "
end
print("m_Output=" .. m_Output)


os.execute("pause")

-- endregion

猜你喜欢

转载自blog.csdn.net/qq_37273889/article/details/85636495