一种新奇的数值排序算法

对于支持 稀疏数组(sparse array) 的程序语言来说,有一种理论上可行的排序算法可以用,具体算法思想如下:
构建一个空数组(lua里是 table),用数组下标来表示数据情况,数组的值来表示出现次数,然后只要将未排序数组里的数据依此对应进去,就排序好了,这个对应后的数组稍作处理就可以得到目标数据,感觉效率很高,但算法的通用性挺糟糕的。

lua的具体实现代码:

function sort(arr,num)
    -- build temp array.
    local temp = {}
    for i,v in pairs(arr) do
        if temp[v] == nil then
            temp[v] = 0
        end
        temp[v] = temp[v] + 1
    end
    -- Sort (Only can be in ascending order)
    local i = 0
    local c = 1
    while c <= num do
        if temp[i] ~= nil then
            while temp[i] > 0 do
                arr[c] = i
                c = c + 1
                temp[i] = temp[i] - 1
            end
        end
        i = i + 1
    end
end

使用:

local arr = {}
local num = 100

local min = 1
local max = 1000

math.randomseed(os.time())

function init(arr,num,min,max)
    local i = 0
    for i = 1,num do
        arr[i] = math.random(min,max)
    end
end

init(arr,num,min,max)

local out_str = ""
for i,v in pairs(arr) do
    --print("["..i.."] = "..v)
    out_str = out_str..v..","
    if i % 20 == 0 then
        out_str = out_str .. "\n"
    end
end

print("Before sorting:")
print(out_str)

sort(arr,num)

out_str = ""
for i,v in pairs(arr) do
    --print("["..i.."] = "..v)
    out_str = out_str..v..","
    if i % 20 == 0 then
        out_str = out_str .. "\n"
    end
end

print("After sorting:")
print(out_str)

输出类似于:

Before sorting:
930,266,744,937,898,751,245,110,95,262,907,562,738,228,37,940,870,268,274,472,
819,838,578,216,488,739,530,28,682,889,236,611,155,980,548,52,731,793,161,825,
54,68,387,791,296,424,731,165,692,5,636,511,842,214,726,330,952,256,358,634,
144,594,245,299,573,792,350,303,584,511,128,637,579,514,428,875,938,159,39,629,
164,675,139,6,888,865,336,840,120,693,473,264,286,718,562,858,509,912,161,93,

After sorting:
5,6,28,37,39,52,54,68,93,95,110,120,128,139,144,155,159,161,161,164,
165,214,216,228,236,245,245,256,262,264,266,268,274,286,296,299,303,330,336,350,
358,387,424,428,472,473,488,509,511,511,514,530,548,562,562,573,578,579,584,594,
611,629,634,636,637,675,682,692,693,718,726,731,731,738,739,744,751,791,792,793,
819,825,838,840,842,858,865,870,875,888,889,898,907,912,930,937,938,940,952,980,

很久之前就有这个想法了,今天终于用代码实现了,看看就好,别用在工作环境里。

posted @ 2018-02-08 10:18  林博士  阅读(263)  评论(0编辑  收藏  举报