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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章