使用Lua解决最大子数组的问题,数据是算法导论里面第四章第一节的数据
t={ 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 }
function FindMaxCrossSubArray(array,low,mid,high)
local leftSum=0
local leftMax=0
local leftIndex=mid
for i=mid,low,-1 do
leftSum=leftSum+array[i]
if(leftSum> leftMax) then
leftMax=leftSum
leftIndex=i
end
end
local rightSum=0
local rightMax=0
local rightIndex=mid
for i=mid+1,high,1 do
rightSum=rightSum+array[i]
if(rightSum> rightMax) then
rightMax=rightSum
rightIndex=i
end
end
return rightMax+leftMax,leftIndex,rightIndex
end
function FindMaxSubArray(array,low,high)
if(low==high) then
return array[low],low,high
end
mid=math.floor((low+high)/2)
local LeftSum,LeftMin,LeftMax=FindMaxSubArray(array,low,mid)
local RightSum,RightMin,RightMax=FindMaxSubArray(array,mid+1,high)
local CrossSum,CrossMin,CrossMax=FindMaxCrossSubArray(array,low,mid,high)
if(LeftSum>=RightSum and LeftSum>=CrossSum) then
return LeftSum,LeftMin,LeftMax
elseif(RightSum>=LeftSum and RightSum>=CrossSum) then
return RightSum,RightMin,RightMax
else
return CrossSum,CrossMin,CrossMax
end
end
sum,left1,right1=FindMaxSubArray(t,1,#t)
print('最大子数组总和'..sum..' 左起'..left1..'右至'..right1)
注意:本来第一次一直结果不成功,下面是结果:
正确结果应是:sum:43,leftIndex: 8,rightIndex: 11。
显示结果34,leftIndex: 8, rightIndex: 16
分析: 最初在FindMaxSubArray()函数里,如下,都没有声明是本地变量,导致了结果一直被覆盖,出现了错误的结果
LeftSum,LeftMin,LeftMax=FindMaxSubArray(array,low,mid)
RightSum,RightMin,RightMax=FindMaxSubArray(array,mid+1,high)
CrossSum,CrossMin,CrossMax=FindMaxCrossSubArray(array,low,mid,high)