LUA 排序算法和性能分析[3]:选择排序算法

来源:互联网 发布:在日韩国人 知乎 编辑:程序博客网 时间:2024/05/17 07:58

选择排序算法

时间开销:中等

稳定性:

复杂度:


math.randomseed(os.time());local real_print = print;local nLine = 0;function print(...)    real_print(nLine, ...)    nLine = nLine + 1;endlocal t = {}local function dump()    -- print(table.concat(t, ","));end;for i = 1, 256 do    table.insert(t, math.random(i), i);endfunction 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