首先谈一谈在实现中遇到几个问题和c++不同且容易误用的点:
1. lua语言中,整型计算可以得出浮点型的结果,可以使用math.floor向下取整,或者math.ceil向上取整
local middle = math.floor((right - left + 1) / 2) + left
2.lua语言中,局部变量不加 local 会被视为全局变量,例如middle如果没有加 local 声明,那么它的值在递归调用过程中都是共享的
middle = math.floor((right - left + 1) / 2) + left
完整代码:
1 function merge(arr, left, right, middle, result) 2 local resultIndex = left 3 local arrLeftIndex = left 4 local arrRightIndex = middle 5 -- 用临时的result数组做插入排序 6 while (arrLeftIndex <= middle - 1 and arrRightIndex <= right) do 7 if (arr[arrLeftIndex] > arr[arrRightIndex]) then 8 result[resultIndex] = arr[arrRightIndex] 9 arrRightIndex = arrRightIndex + 1 10 else 11 result[resultIndex] = arr[arrLeftIndex] 12 arrLeftIndex = arrLeftIndex + 1 13 end 14 resultIndex = resultIndex + 1 15 end 16 17 while (arrLeftIndex <= middle - 1) do 18 result[resultIndex] = arr[arrLeftIndex] 19 resultIndex = resultIndex + 1 20 arrLeftIndex = arrLeftIndex + 1 21 end 22 23 while (arrRightIndex <= right) do 24 result[resultIndex] = arr[arrRightIndex] 25 resultIndex = resultIndex + 1 26 arrRightIndex = arrRightIndex + 1 27 end 28 29 --排序结果保存到原数组 30 for i = left, right do 31 arr[i] = result[i] 32 end 33 end 34 35 function mergeSort(arr, left, right) 36 --print(left.." "..right) 37 local result = {} 38 if (1 == right - left) then 39 if (arr[left] > arr[right]) then 40 local temp = arr[left] 41 arr[left] = arr[right] 42 arr[right] = temp 43 end 44 elseif (0 ~= left - right) then 45 local middle = math.floor((right - left + 1) / 2) + left 46 --print(left.." "..right.." "..middle) 分解 47 mergeSort(arr, left, middle - 1, result) 48 mergeSort(arr, middle, right, result) 49 --print(left.." "..right.." "..middle) 合并 50 merge(arr, left, right, middle, result) 51 end 52 end 53 54 local unsortedArray = {2, 1, 3, 5, 6, 9, 8, 7, 4} 55 56 mergeSort(unsortedArray, 1, #unsortedArray) 57 58 for i,v in ipairs(unsortedArray) do 59 io.write(tostring(v).." ") 60 end