1、汉诺塔算法
-- 汉诺塔算法
-- n:移动圆盘的个数
-- from:源柱
-- to:目标柱
-- fuzhu:辅助柱
function ChangePage(n, from, to, fuzhu)
if(n == 1) then
print(string.format("移动圆盘从:%s 到 %s", from, to))
return
end
ChangePage(n - 1, from, fuzhu, to)
print(string.format("移动圆盘从:%s 到 %s", from, to))
ChangePage(n - 1, fuzhu, to, from)
end
ChangePage(5,'A', 'B', 'C')
2、判断一个数组是否为顺序(递给求解)
-- tab:目标表
-- len:表的长度
function IsArraySortedOrder(tab, len)
if(len == 1) then return true end
if(tab[len] < tab[len - 1]) then return false end
return IsArraySortedOrder(tab, len - 1)
end
tab = {3, 2, 4, 1, 7, 5, 8, 0, 14, 11, 10}
print(IsArraySortedOrder(tab, #tab))
3、冒泡排序(改进的)
-- 冒泡排序
-- tab:目标表
-- len:表的长度
-- count:测试排序执行的次数
function BubbleSort(tab, len)
local isSort = true
local count = 0
for i = 1, len do
for j = 1, len - i do
count = count + 1
if(tab[j] > tab[j + 1])then
isSort = false
local temp = tab[j]
tab[j] = tab[j + 1]
tab[j + 1] = temp
end
end
if(isSort) then
break
else
isSort = true
end
end
print(table.concat(tab, ','))
print(count)
end
--tab = {3, 2, 4, 1, 7, 5, 8, 0, 14, 11, 10}
tab = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
BubbleSort(tab, #tab)
4、选择排序
-- 选择排序
function Selection(tab, len)
local min = 1;
local temp
for i = 1, len - 1 do
min = i
for j = i + 1, len do
if tab[min] > tab[j] then
min = j
temp = tab[i]
tab[i] = tab[j]
tab[j] = temp
end
end
end
print(table.concat(tab, ','))
end
tab = {3, 2, 4, 1, 7, 5, 8, 0, 14, 11, 10}
Selection(tab, #tab)