以下是我在ruby中实现合并排序算法的代码。运行后我收到以下错误。请帮我解决动态常量错误。
我在终端遇到的错误是:
ruby merge.rb
merge.rb:8: dynamic constant assignment
Li=Array.new(n1.object_id)
^
merge.rb:9: dynamic constant assignment
Ri=Array.new(n2.object_id)
^
我的代码:
def merge(list,l,m,r)
i
j
k
n1 = m - l + 1
n2 = r - m
Li=Array.new(n1)
Ri=Array.new(n2)
0.upto(n1-1)do |i|
Li[i] = list[l + i]
end
0.upto(n2-1)do |j|
Ri[j] = list[m + 1+ j]
end
i = 0
j = 0
k = l
while i < n1 && j < n2
if Li[i] <= Ri[j]
list[k] = Li[i]
i=i+1
else
list[k] = Ri[j]
j=j+1
end
k=k+1
end
while i < n1
list[k] = Li[i]
i=i+1
k=k+1
end
while j < n2
list[k] = Ri[j]
j=j+1
k=k+1
end
end
def mergeSort(list,l,r)
if (l < r)
m = l+(r-l)/2
mergeSort(list, l, m)
mergeSort(list, m+1, r)
merge(list, l, m, r)
end
end
def printArray(list, size)
0.upto(size-1) do |i|
puts list[i]
end
end
list = Array[12, 11, 13, 5, 6, 7]
puts "Given array is"
printArray(list,list.size)
mergeSort(list, 0, list.size - 1)
puts "Sorted array is"
printArray(list,list.size)
答案 0 :(得分:0)
Li=Array.new(n1)
Ri=Array.new(n2)
以大写字母开头的名称是常量。错误告诉您正在尝试修改常量。更改名称Li
和Ri
,以便它们以小写字母开头。