问题描述
我刚开始在MIT算法导论课程通过网上公布的材料。随着当然,我也决定学习/通过编码算法是提高我的红宝石技能。
我给出的第一种算法,这是插入排序,和我有以下code打完了,但我收到此错误,当我运行它:
高清insertionsort(NUM)
对于j在2..num.length
键= NUM [J]。
I =的J - 1
而I> 0和num [Ⅰ]≥键
NUM [I + 1] = NUM [I]
I = I - 1
结束
NUM [I + 1] =键
结束
把NUM
结束
数= [23,34,46,87,12,1,66]
insertionsort(数字)
我敢肯定,这是一个相当基本的问题,但我就是不能掌握它是什么的时刻。任何帮助或提示将非常AP preciated。
正在overruning你的数组的边界。你给出的例子是假设1索引的数组,但是在Ruby的数组是0索引。第一行应该是
其中j在1 ... num.length
I have just started the MIT Introduction to Algorithms course through the material posted online. Along with the course I have also decided to learn/enhance my Ruby skills by coding the algorithms in it.
I am on the first algorithm given, which is Insertion sort, and I have the following code typed up but I am getting this error when I run it:
def insertionsort(num)
for j in 2..num.length
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
puts num
end
numbers = [23,34,46,87,12,1,66]
insertionsort(numbers)
I'm sure it is a fairly basic problem but I just can't grasp what it is at the moment. Any help or tips would be very much appreciated.
You are overruning the bounds of your array. The example you were given was assuming 1-indexed arrays, but arrays in ruby are 0-indexed. The first line should be
for j in 1...num.length
这篇关于学习插入排序在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!