最近回头看了下排序算法,用lua实现,随手记录一下
a = {1,3,5,2,6,8,10,3,6,20}
--冒泡排序(从头到尾排序,相邻两个互相对比)
local function MaoPao(t, isIncrease)
local count = #a
for j = 1, count -1 do
for i = 1, count - 1 do
local pre = a[i]
local nex = a[i+1]
if isIncrease and pre > nex then --递增
a[i] = nex
a[i + 1] = pre
elseif not isIncrease and pre < nex then --递减
a[i] = nex
a[i + 1] = pre
end
end
end
end
local function PrintTab(t)
for k, v in pairs(t) do
print(v)
end
end
print("Decrease")
MaoPao(a, false)
PrintTab(a)
print("Increase")
MaoPao(a, true)
PrintTab(a)