【问题标题】:Making my own sort method in Ruby在 Ruby 中创建我自己的排序方法
【发布时间】:2013-11-23 03:16:58
【问题描述】:

所以我是编程新手,我正在研究 Chris Pine 的 Learn to Program,它教授 Ruby。我在第 10 章尝试为数组创建自己的方法。我完全不知所措,并尝试根据他建议的答案来模拟我的。摆弄之后,我无法获得输出。我运行程序,它就结束了。我什至尝试使用他的代码,但它给了我同样的问题。

这是我目前所拥有的。

unsorted_array = ['gamma', 'delta', 'beta', 'alpha', 'zeta']
sorted_array = []

def sort some_array 
  recursive_sort(some_array, [])
end


def recursive_sort(unsorted_array, sorted_array) 
  if unsorted_array.length <= 0
    return sorted_array 
  end

  still_unsorted =[]
  smallest = unsorted_array.pop
  sorted_array = []

  unsorted_array.each do |tested_obj|
    if '#{tested_obj}' > smallest
      sorted_array.push(smallest)
    else
      still_unsorted.push(smallest)
      smallest = unsorted_array.pop
    end
  end
    recursive_sort(still_unsorted, sorted_array)
end


puts sort(recursive_sort(unsorted_array, sorted_array))

任何建议将不胜感激。

【问题讨论】:

  • 当您调用 pop 时,您正在改变原始数组。这是你的意图吗?

标签: ruby sorting methods


【解决方案1】:

以下是对您的代码的一些观察:

  • 因为test_obj是一个字符串,所以'#{tested_obj}'#{tested_obj}一样,就和tested_obj一样。
  • 声明sorted_array = [] 无效。作为局部变量,它不在方法recursive_sort 的范围内。该方法接收一个它调用sorted_array 的数组,因此无论如何您都不希望它初始化。
  • 您不需要创建新数组still_unsorted;只需将元素从unsorted_array 转移到sorted_array

下面我已经修复并收紧了你的代码。

  def recursive_sort(unsorted_array, sorted_array = []) 
    return sorted_array unless unsorted_array.length > 0
    smallest = unsorted_array.min 
    unsorted_array.each {|e| sorted_array << e if e == smallest}
    unsorted_array.delete(smallest)
    recursive_sort(unsorted_array, sorted_array)
  end

  unsorted_array = ['gamma', 'alpha', 'delta', 'beta', 'gamma', 'alpha', 'zeta']
  p recursive_sort unsorted_array
    #  => ["alpha", "alpha", "beta", "delta", "gamma", "gamma", "zeta"]

这是发生了什么:

  • 通过为recursive_sort (sorted_value) 的第二个参数提供默认值[](一个空数组),就不需要您之前使用的方法sort
  • 如果排序完成,则返回sorted_array(与return sorted_array if unsorted_array.length == 0 相同)。
  • 使用Enumerable#min 查找未排序项的最小值(smallest)。
  • unsorted_arraysmallest 的每个实例添加到sorted_array
  • 删除smallestunsorted_array 中的所有实例。
  • 再次调用相同的方法,删除下一​​个最小的未排序项,等等。

注意

  unsorted_array.each {|e| sorted_array << e if e == smallest}

可以用许多不同的方式表达。这是一个:

  sorted_array += [smallest]*(unsorted_array.count {|e| e == smallest})

要了解它是如何工作的,假设smallest = 'alpha'。那么

  unsorted_array.count {|e| e == 'alpha'} # => 2

所以上面的表达式是:

  sorted_array += ['alpha']*2

这是

  sorted_array += ['alpha', 'alpha']

将两个"alpha" 添加到sorted_array

【讨论】:

  • 非常感谢 Cary,你帮了大忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
相关资源
最近更新 更多