Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

algorithm - Learning Insertion Sort in Ruby

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:

insertionsort.rb:5:in `>': comparison of Fixnum with nil failed (ArgumentError)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...