2015-10-19 62 views
0
排序程序

我已經看到了一個紅寶石以下排序程序,但我不認爲我完全理解它是如何工作:關於Ruby

def sort arr 
    rec_sort arr, [] 
end 

def rec_sort unsorted, sorted 

    if unsorted.length <= 0 
     return sorted 
    end 
    smallest = unsorted.pop 
    still_unsorted = [] 

    unsorted.each do |tested| 
     if tested < smallest 
      still_unsorted.push smallest 
      smallest = tested 
     else 
      still_unsorted.push tested 
     end 
    end 
    sorted.push smallest 
    rec_sort still_unsorted, sorted 
end 

puts sort ["satoshi", "Bitcoin", "technology", "universe", "smell"] 

=> Bitcoin 
    satoshi 
    smell 
    technology 
    universe 

但是,當我改變「rec_sort」的第一個參數方法從「still_unsorted」(如上面所指出的),以「未分類」,程序給出:

=> Bitcoin 
    Bitcoin 
    Bitcoin 
    Bitcoin 
    satoshi 

據我所知,每個循環選擇單詞「比特幣」第一(因爲它的確會先來排序時),和「比特幣」將被放入「排序」的數組中。我不明白的是爲什麼這裏有幾個「比特幣」,因爲它應該在每個循環的第一次迭代中被排除在「未排序」數組之外,因此不能出現在下面的迭代中,使得「比特幣」不可能在「排序」陣列中多次出現。

你能告訴我是什麼讓這兩個如此不同? 任何建議將不勝感激。謝謝。

+0

據我瞭解它的遞歸實現[冒泡排序]的(https://en.wikipedia.org/wiki/Bubble_sort)。除了語句'unsorted.pop'外,沒有修改'unsorted',只是複製到'still_unsorted'中,除了該數組中的最小元素 – Minato

+0

你知道puts [「satoshi」,「比特幣「,」技術「,」宇宙「,」嗅覺「]。sort給你你需要的東西,在你的例子中使用的排序算法看起來很笨拙,如果你對排序技術感興趣, – peter

回答

0

still_unsorted數組已將smallest元素刪除,但unsorted數組只刪除了其最後一個元素。

0

據我瞭解它的遞歸實現bubble sort。併爲你的困惑unsorted不被修改,除了聲明unsorted.pop但只被複製到still_unsorted除外數組中最小的元素

我在[3,1,2]幹運行此爲您

unsorted = [3,1,2] 
sm = unsorted.pop # sm = 2 unsorted = [3,1] 
still_unsorted = [] 
#after loop unsorted.each 
# still_unsorted = [2,3] 
# unsorted = [3,1] 
# sm = 1 
# sorted = [1] 

做下2次迭代,你就會明白髮生了什麼