def recursive_insert(arr)
return arr if arr.size<=1
recursive_insert(arr[0,arr.size-1])
i=arr.size-1
while arr[i-1]>arr[i] and i>0
arr[i],arr[i-1] = arr[i-1],arr[i]
i-=1
end
arr
end
arr=[5,4,3,2,6,1]
x=recursive_insert(arr)
puts x.inspect
This doesn’t work. I suspect that Ruby has a pass by reference mechanism, which prevents my arr variable being updated for each recursive call.
How do I solve this? I have so many difficulties writing a recursive function in Ruby.
This:
returns a copy of part of
arrand changes to that copy will not be reflected inarr. So, your recursive step does nothing useful and your method is equivalent to this:and that gets the 1 in the right place and that’s all.