Lua中寫(xiě)排序算法實(shí)例(選擇排序算法)
早在12年的時(shí)候,學(xué)過(guò)一個(gè)月的lua,當(dāng)時(shí)看的是《programming in lua》,一直沒(méi)用過(guò),然后就忘了?,F(xiàn)在我下定決心重新學(xué)習(xí)它。
時(shí)間久了,對(duì)編程的熱情也隨之消失殆盡,很難找回當(dāng)初編程的樂(lè)趣了。近來(lái)一放假就玩英雄聯(lián)盟,太浪費(fèi)時(shí)間,玩?zhèn)€十來(lái)局一天就過(guò)去了,渾渾噩噩的,這實(shí)在不是我想過(guò)的。所以,今天我把它卸載了。如果你也是英雄聯(lián)盟玩家,希望你不要沉迷其中。
從事游戲開(kāi)發(fā)還不到一年,已經(jīng)有點(diǎn)厭倦了,同事們一致認(rèn)為游戲公司普遍很浮躁,有些小公司沒(méi)有一點(diǎn)技術(shù)氛圍。我知道的有些程序員,技術(shù)遠(yuǎn)遠(yuǎn)比普通游戲程序員強(qiáng),由于靠譜的游戲公司太少而做其他開(kāi)發(fā)了。
吐槽完了,用lua 寫(xiě)個(gè)選擇排序:
--select sort
function select_sort(t)
for i=1, #t - 1 do
local min = i
for j=i+1, #t do
if t[j] < t[min] then
min = j
end
end
if min ~= i then
t[min], t[i] = t[i], t[min]
end
end
end
tb = {77, 99, 2, 334, 22, 32, 9}
print("-------------before--------------")
print(table.concat(tb, " "))
print("-------------after---------------")
select_sort(tb)
print(table.concat(tb, " "))
table帶有個(gè)sort函數(shù),手冊(cè)說(shuō)明如下:
Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead.
The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.
因此你也可以這么寫(xiě):
function comp(a, b)
return a < b
end
table.sort(tb, comp)
當(dāng)然,通常你可以使用匿名的函數(shù)
table.sort(tb, function(a, b)
return a < b
end)
完
相關(guān)文章
使用nginx+lua實(shí)現(xiàn)信息訪問(wèn)量統(tǒng)計(jì)
這篇文章主要介紹了使用nginx+lua實(shí)現(xiàn)信息訪問(wèn)量統(tǒng)計(jì),功能很簡(jiǎn)單,代碼也很簡(jiǎn)潔,有需要的小伙伴可以參考下,然后自由擴(kuò)展。2015-03-03Lua 數(shù)學(xué)庫(kù)的所有函數(shù)功能作用一覽
這篇文章主要介紹了Lua 數(shù)學(xué)庫(kù)的所有函數(shù)功能作用一覽,本文羅列了lua數(shù)學(xué)庫(kù)的所有函數(shù),并對(duì)每個(gè)函數(shù)的功能作用做了簡(jiǎn)短描述,需要的朋友可以參考下2015-06-06Lua字符串庫(kù)中的幾個(gè)重點(diǎn)函數(shù)介紹
這篇文章主要介紹了Lua字符串庫(kù)中的幾個(gè)重點(diǎn)函數(shù)介紹,本文講解了幾個(gè)最常用的強(qiáng)大的字符串函數(shù)find、match、gsub、gmatch,需要的朋友可以參考下2014-09-09lua讀取redis數(shù)據(jù)的null判斷示例代碼
最近在工作中遇到了一個(gè)問(wèn)題,通過(guò)查找相關(guān)資料才得知原因是因?yàn)榉祷亟Y(jié)果的問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于lua讀取redis數(shù)據(jù)的null判斷的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-09-09