2013-11-23 29 views
0

所以我對編程很陌生,我正在研究Chris Pine的Learn to Program,它教Ruby。我在第10章試圖爲數組創建自己的方法。我完全喪失了工作,並試圖對他的建議答案進行建模。在擺弄之後,我無法獲得輸出。我運行該程序,它只是結束。我甚至嘗試過使用他的代碼,它給了我同樣的問題。在Ruby中創建我自己的排序方法

這是我到目前爲止。

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)) 

任何意見,將不勝感激。

+0

當你調用'pop'時,你正在改變原始數組。這是你的意圖嗎? – Phrogz

回答

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你以前有。
  • 如果排序完成(與return sorted_array if unsorted_array.length == 0相同),則返回sorted_array
  • 使用Enumerable#min查找未排序項目的最小值(smallest)。
  • smallest的每個實例都添加到unsorted_arraysorted_array之間。
  • unsorted_array中刪除smallest的所有實例。
  • 調用相同的方法再次,去除下一個最小的未分類項等

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"「s到sorted_array

+0

非常感謝卡瑞,你一直很大的幫助。 – Tsiege

相關問題