2009-10-08 61 views
0

好的,我一直在Ruby中使用不同的排序算法。主要是變化快速排序。我有一個選擇隨機樞軸的雙重旋轉快速排版。所以當隨機樞紐着陸在數組的開始或結尾時,奇怪的事情開始發生。我做了一些調查,並將其歸結爲這種奇怪的現象。RUBY:數組和平行分配的奇怪問題

//irb output    #using Ruby 1.8.6 and irb 0.9.5 
irb> foo = [1,2,3,4]  #create my array, very generic for an example 
=> [1, 2, 3, 4] 
irb> foo[0],foo[1],foo[2],foo[3] = foo[1],foo[0],foo[3],foo[2] 
=> [2, 1, 4, 3]   #array swaps inside values with edge values fine. 
irb> foo 
=> [2, 1, 4, 3]   #values have changed correctly. 
irb> foo = [1,2,3,4]  #reset values 
=> [1, 2, 3, 4]   #next I am going to try and swap the element foo[0] with itself 
irb> foo[0],foo[0],foo[2],foo[3] = foo[0],foo[0],foo[3],foo[2] 
=> [1, 1, 4, 3]   #for some reason elements foo[0] and foo[1] take on the value of foo[0] 
irb> foo  #check our array again 
=> [1, 2, 4, 3]   #neither value foo[0] nor foo[1] are altered. 

任何人都可以解釋爲什麼會發生這種情況嗎?

只是要說清楚,我並不是在尋求幫助實施快速排序。

編輯: 要,希望,使這裏的問題更清楚的是實施的樣子:

# error caused when (pseudo-code) pivot1|pivot2 == start|end 
foo[start], foo[pivot1], foo[pivot2], foo[end] = 
    foo[pivot1], foo[start], foo[end], foo[pivot2] 

回答

7

這裏沒什麼奇怪的。請參閱下面的評論。

=> [1, 2, 3, 4]   
irb> foo[0],foo[0],foo[2],foo[3] = foo[0],foo[0],foo[3],foo[2] 

#this is return value from the last expression ,that is the 
#parallel assignment , the value of that expression is [1, 1, 4, 3] , 
#not the value of foo 
=> [1, 1, 4, 3]   
irb> foo  

#In the last parallel assignment, you set f[0] to f[0] , did not change f[1] , 
#you swapped f[2],f[3] .This is exactly what you did . 
=> [1, 2, 4, 3]  
+0

啊,我明白了。現在我正在踢自己,因爲我應該自己想出來。猜猜我回到了繪圖板來找出我的問題。 – sanscore 2009-10-08 08:33:01

+0

我認爲並行賦值的返回值是數組的新值。每天學習新事物,是吧? – Rayne 2009-10-08 08:36:16

-1

你已經做出了錯誤類型

富[0],富[ 0]而不是foo [0],foo [1]!

+0

不,他沒有。他正在嘗試與自己交換[0]。 – Rayne 2009-10-08 08:13:05

+0

劃痕,我讀他的代碼錯了。抱歉。 – Rayne 2009-10-08 08:14:18

+0

我向你保證一切都輸入正確。在雙重支點的實施中,它看起來更像這樣。其中開始== pivot1 – sanscore 2009-10-08 08:15:36