Lua实现经典排序算法

引用:https://www.toutiao.com/a6593273307280179715/?iid=6593273307280179715#comment_area

 

冒泡排序

--实现冒泡排序
function MaoPaoSort( table_temp , r)

    repeat

        for i = 1 , r - 1 do

                --交换值
                if(table_temp[i] > table_temp[i+1]) then

                    table_temp[i] , table_temp[i+1] = table_temp[i+1] , table_temp[i] 

                end

        end

        r = r - 1

    until(r == 2)

end

--检测冒泡排序
temp = {3,44,38,5,47,15,36,26}

MaoPaoSort(temp,#temp)

for i=1,#temp do

    io.write(temp[i].." ")
    
end

 

快速排序

function QuickPaiXu(table_4 , l , r)

    local x = table_4[l]

    while (l < r) do
        while (l < r and table_4[r] >= x) do
            r = r - 1
        end

        if (l < r) then
            table_4[l] , table_4[r] = table_4[r] , table_4[l]
            l = l + 1
        end

        while(l < r and table_4[l] <= x) do
            l = l + 1
        end

        if (l < r) then
            table_4[r] = table_4[l]
            r = r - 1 
        end        
    end

    table_4[l] = x

    return l
end


function quick_sort1(table_5,l,r)

    if (l < r) then

        i = QuickPaiXu(table_5,l,r)

        quick_sort1(table_5,l,i-1)

        quick_sort1(table_5,i+1,r)

    end

end

 

选择排序

--实现选择排序
function SerachSort( Table_temp )

	for j = 1 , #Table_temp - 1 do

		local minimumIndex = j

		for i = j , #Table_temp - 1 do

			if ( Table_temp[minimumIndex] > Table_temp[i+1]) then

				minimumIndex = i + 1

			end
		end

		--交换一次值
		Table_temp[j] , Table_temp[minimumIndex] = Table_temp[minimumIndex] , Table_temp[j]

	end

end

--检验选择排序
temp = {10,20,3,54,5,60,14,16}

SerachSort(temp)


for i = 1,#temp do

	io.write(temp[i].." ")

end

插入排序


--实现插入排序
function InsertSort( table_temp )

	for i = 1, #table_temp - 1 do

		local current = table_temp[i+1]

		preIndex = i

		while (preIndex >= 1 and current < table_temp[preIndex]) do

			table_temp[preIndex + 1] = table_temp[preIndex];

			preIndex = preIndex - 1

		end

		table_temp[preIndex + 1] = current
	end

end

--测试插入排序

temp = {10,20,3,54,5,60,14,16}

InsertSort(temp)


for i = 1,#temp do

	io.write(temp[i].." ")

end

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值