lua 实现的几个简单的排序算法

来源:互联网 发布:网络直播平台 论文 编辑:程序博客网 时间:2024/05/29 10:21

都是按从小到大排序的。

-- 插入排序

function insertSort(array)

    local j,target

    local n = #array

    for i =2,n do

        j = i

        target = array[i]

        while (j >1and target <array[j -1])do

            array[j] =array[j -1]

            j = j -1

        end

        array[j] =target

    end

end


-- 希尔排序(分组插入排序)

function shellSort(array)

    local j,target

    local n = #array

    -- 对每组插入排序

    local functionsortGap(gap)

        for i =gap +1, n do

            j = i

            target = array[i]

            while (j >gapand target <array[j -gap])do

                array[j] =array[j -gap]

                j = j - gap

            end

            array[j] =target

        end

    end


    local gap = math.max(math.floor(n /2),1) -- 增量

    while truedo

        sortGap(gap)

        if gap ==1then -- 最后一次gap必须为1

            break

        end

        gap = math.max(math.floor(gap /2),1)

    end

end


-- 选择排序

function selectSort(array)

    local temp

    local n = #array

    for i =1,n do

        for j =i +1, n do

            if array[i] >array[j]then

                temp = array[i]

                array[i] =array[j]

                array[j] =temp

            end

        end

    end

end


-- 冒泡排序

function maoPaoSort(array)

    local temp

    local n = #array

    for i =1,n do

        for j =1,n - i do

            if array[j] >array[j +1] then

                temp = array[j]

                array[j] =array[j +1]

                array[j +1] =temp

            end

        end

    end

end


-- 快速排序(交换排序)

function quickSort(array)

    local n = #array

    local functionsort(l,r)

        if l <rthen

            local i = l

            local j = r

            local x = array[l]

            while i < j do

                while (i <jand array[j] >=x) do

                    j = j - 1

                end

                if i < j then

                    array[i] =array[j]

                    i = i + 1

                end


                while (i <jand array[i] <x) do

                    i = i + 1

                end

                if i < j then

                    array[j] =array[i]

                    j = j - 1

                end

            end

            array[i] =x

            sort(l,i -1)

            sort(i +1,r)

        end

    end


    sort(1,n)

end


0 0
原创粉丝点击