对不起也许是一个简单的问题,但我无法弄清楚。我有一个程序对数组进行排序:
def insertionsort(num)
for j in 1..(num.length - 1)
key = num[j]
i = j - 1
while i >= 0 and num[i] > key
num[i+1] = num[i]
i = i - 1
end
num[i+1] = key
end
end
ar = Array.new(10) { rand(1...11) }
insertionsort(ar)
insertionsort(ar)
insertionsort(ar)
insertionsort(ar)
insertionsort(ar)
p ar
但是在第一次排序后插入(ar)我必须使用相同的数组,但是在第一个排序变量ar之后需要排序数组
答案 0 :(得分:0)
只需克隆你的数组,就像以前一样保留第一个数组:
def insertionsort(num)
res = num.dup
for j in 1..(res.length - 1)
key = res[j]
i = j - 1
while i >= 0 and res[i] > key
res[i+1] = res[i]
i = i - 1
end
res[i+1] = key
end
res
end
ar = Array.new(10) { rand(1...11) }
res = insertionsort(ar)
p ar
p res