选择排序算法
时间开销:中等
稳定性:
复杂度:
math.randomseed(os.time());
local real_print = print;
local nLine = 0;
function print(...)
real_print(nLine, ...)
nLine = nLine + 1;
end
local t = {}
local function dump()
-- print(table.concat(t, ","));
end;
for i = 1, 256 do
table.insert(t, math.random(i), i);
end
function table_sort()
table.sort(t);
dump()
end
-- table_sort() -- 0.3
-- 冒泡排序
function bubble_sort()
print("冒泡排序")
local n = #t;
for j = 1, n - 1 do
for i = 1, n - j do
if t[i] > t[i+1] then
t[i], t[i+1] = t[i+1], t[i];
dump()
end;
end;
end;
dump()
end;
-- bubble_sort(); -- 5.7
-- 选择排序
function select_sort()
print("选择排序")
local n = #t;
for i = 0, n - 2 do
local min = i;
for j = i + 1, n - 1 do
if t[min+1] > t[j+1] then
min = j;
end;
end;
if (min ~= i) then
t[min+1], t[i+1] = t[i+1], t[min+1];
dump()
end;
end;
dump()
end;
-- select_sort() -- 3.4