好的,我一直在搞乱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.
任何人都可以解释为什么会这样吗?
为了清楚起见,我不是在寻求帮助实施quicksort。
修改 希望能够让问题更清楚的是实现的样子:
# 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]
答案 0 :(得分: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]
答案 1 :(得分:-1)
您犯了类型错误
foo [0],foo [0]而不是foo [0],foo [1]!