我正在尝试通过编写基本的归并排序来学习 Lua,但由于我对归并排序也不熟悉,因此遇到了一些问题。
编码:
arr = {}
status = 0
function return_first_half (list)
size = #list
size = size / 2
t = {}
for var = 1, size, 2 do
t[var] = list[var]
end
return t
end
function return_last_half (list)
size = #list
i = size / 2
t = {}
for var = size, i, -1 do
t[var] = list[var]
end
return t
end
function msort (list)
size = #list
first_half = {}
last_half = {}
if (size <= 1) then
return list
end
first_half = msort(return_first_half(list))
last_half = msort(return_last_half(list))
if (#first_half == 1) then
if (#last_half == 1) then
if (first_half[1] > last_half[1]) then
arr[status] = first_half[1]
status = status + 1
arr[status] = last_half[1]
status = status + 1
end
if (first_half[1] < last_half[1])then
arr[status] = last_half[1]
status = status + 1
arr[status] = first_half[1]
status = status + 1
end
end
end
end
function main ()
list = {}
for i = 1, 8, 1 do
list[i] = io.read()
end
msort(list)
for i = 1, #arr, 1 do
print (arr[i])
end
end
main()
当我将输入 8 降为 1 时,它会打印 nil 并退出。有什么帮助吗?
编辑:修复了数组长度和地址的问题,它现在在该行返回堆栈溢出:
first_half = msort(return_first_half(list))