最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Lua中寫排序算法實例(選擇排序算法)

 更新時間:2015年04月23日 10:41:01   投稿:junjie  
這篇文章主要介紹了Lua中寫排序算法實例,本文用一個選擇排序算法為例講解如何在Lua中寫一個排序算法,需要的朋友可以參考下

早在12年的時候,學(xué)過一個月的lua,當(dāng)時看的是《programming in lua》,一直沒用過,然后就忘了?,F(xiàn)在我下定決心重新學(xué)習(xí)它。

時間久了,對編程的熱情也隨之消失殆盡,很難找回當(dāng)初編程的樂趣了。近來一放假就玩英雄聯(lián)盟,太浪費時間,玩?zhèn)€十來局一天就過去了,渾渾噩噩的,這實在不是我想過的。所以,今天我把它卸載了。如果你也是英雄聯(lián)盟玩家,希望你不要沉迷其中。

從事游戲開發(fā)還不到一年,已經(jīng)有點厭倦了,同事們一致認(rèn)為游戲公司普遍很浮躁,有些小公司沒有一點技術(shù)氛圍。我知道的有些程序員,技術(shù)遠(yuǎn)遠(yuǎn)比普通游戲程序員強,由于靠譜的游戲公司太少而做其他開發(fā)了。

吐槽完了,用lua 寫個選擇排序:

復(fù)制代碼 代碼如下:

--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帶有個sort函數(shù),手冊說明如下:
復(fù)制代碼 代碼如下:

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.

因此你也可以這么寫:
復(fù)制代碼 代碼如下:

function comp(a, b)
     return a < b
end

table.sort(tb, comp)


當(dāng)然,通常你可以使用匿名的函數(shù)
復(fù)制代碼 代碼如下:

table.sort(tb, function(a, b)
     return a < b
end)

相關(guān)文章

  • Lua中的函數(shù)淺析

    Lua中的函數(shù)淺析

    這篇文章主要介紹了Lua中的函數(shù),包括函數(shù)聲明、函數(shù)參數(shù)、多重返回值、變長參數(shù)、具名實參、閉包函數(shù)等內(nèi)容,需要的朋友可以參考下
    2014-09-09
  • 最新評論

    清丰县| 上思县| 光山县| 彰武县| 福安市| 湛江市| 宜城市| 利津县| 凤翔县| 吉木乃县| 睢宁县| 海伦市| 讷河市| 剑川县| 纳雍县| 禹州市| 定南县| 宁陕县| 通海县| 勐海县| 平江县| 贵溪市| 阿拉善右旗| 高陵县| 定日县| 栾川县| 新竹市| 当涂县| 祥云县| 通辽市| 吉水县| 沅陵县| 遂宁市| 三穗县| 龙胜| 金塔县| 永川市| 拜城县| 香河县| 晋江市| 榆中县|