我决定开始学习一些ruby,并尝试在ruby(2.3.0)中使用插入排序版本。但是,当我的程序检查位置和是否交换值时,它会返回“>”的nomethoderror。更具体地说:
./rubyInsertSort.rb:28:in `block in sort': undefined method `>' for 1..4:Range (NoMethodError)
from ./rubyInsertSort.rb:26:in `each'
from ./rubyInsertSort.rb:26:in `sort'
from ./rubyInsertSort.rb:22:in `main'
from ./rubyInsertSort.rb:40:in `<main>'
下面是排序方法的代码:
def sort(input, valueAmount)
for i in 1..valueAmount
j = i
while j > 0 and input[j - 1] > input[j]
input[j], input[j - 1] = input[j - 1], input[j]
j += -1
end
end
#Output loop
for i in 1..valueAmount
puts "Sort Value #{i} = #{input[i]}" #Outputs the sorted array to the console
end
end
我知道这可能是一些琐碎和非常简单的事情,但我找不到一个问题在这里或其他地方与解决方案,任何帮助将不胜感激!
最佳答案
修改了您的版本
def sort(input, valueAmount)
for i in 1...valueAmount # Added a dot
j = i
while j >= 0 and input[j - 1] > input[j] # >= instead of >
input[j], input[j - 1] = input[j - 1], input[j]
j += -1
end
end
#Output loop
for i in 0...valueAmount # Added a dot
puts "Sort Value #{i} = #{input[i]}" #Outputs the sorted array to the console
end
end
这是我的版本(没有输出)
def insertion_sort!(ary)
return ary if ary.size < 2
1.upto(ary.size - 1) do |i|
i.downto(0) do |j|
break if ary[j - 1] <= ary[j]
ary[j - 1], ary[j] = ary[j], ary[j - 1]
end
end
ary
end