lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Wim Couwenberg wrote:
Below is my sort2 entry for Lua 5.0.2 (submitted). It writes to an arbitrary file or stdout (if not provided).

OK, here is my Bubble Sort contribution for Lua 5.0.2.

------------------------8<----------------------------
#!Lua-5.0.exe
-- APLC Bubble Sort.
-- http://www.kochandreas.com/home/language/tests/BUBBLE.HTM
-- by Philippe Lhoste <PhiLho(a)GMX.net> http://Phi.Lho.free.fr
-- v. 1.0 -- 2004/12/30

function DumpArray(a)
    for i, v in ipairs(a) do
        io.write(v .. ' ')
    end
    print''
end

local array = {}
local input, entryNb, swapNb = nil, 0, 0

-- Input numbers
repeat
    io.write"> "
    input = io.read"*n" -- Read a number, returns nil if not number
    if input ~= nil and input > 0 then
        table.insert(array, input)
        entryNb = entryNb + 1
    else print("End: |" .. (input or "nil") .. "|")
    end
until input == 0 or input == nil or entryNb == 25
print"---" ; DumpArray(array)

-- Sort them
repeat
    swapNb = 0
    for i = 1, entryNb - 1 do
        if array[i] > array[i + 1] then
            array[i], array[i + 1] = array[i + 1], array[i]
            swapNb = swapNb + 1
        end
    end
until swapNb == 0
print"---" ; DumpArray(array)
------------------------>8----------------------------

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --