3

所以我正在尝试学习如何在不使用 .sort 方法的情况下对数组进行排序,这是我目前所拥有的,但中间的数字正在下降。

def  my_sort(num)
for j in 1...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     

end

然后我运行该方法

my_sort([3,1,2])

我明白了

=> 1...3 

但我想要

=> 1,2,3

我究竟做错了什么?

4

2 回答 2

2

You're not returning the modified array, but instead the object fed into your for iterator.

What you're missing is simply leaving the array as the last thing in the method:

def my_sort(num)
  # ...

  num
end

As a note it's usually bad form to wreck the arguments you're given. A more polite function would return a copy.

于 2012-06-14T05:58:58.750 回答
0

插入排序的实际实现必须如下所示:

def my_sort(arr)
  for j in 1...arr.length
    key = arr[j]
    i = j-1
    while i>=0 and arr[i] > key # You used arr[i] = key here instead
      arr[i+1] = arr[i]
      i = i-1
    end 
    arr[i+1] = key
  end 
  arr #return the array
end 
于 2012-06-14T07:41:00.013 回答