Okay, I have been messing around with different sorting algorithms in Ruby; mainly variations quicksort. I have a version of dual pivoted quicksort that picks random pivots. So when the random pivot lands at the beginning or end of the array weird things start happening. I did some investigating and have boiled it down to this strange phenomenon.
//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.
Can anyone explain why this is happening?
Just to be clear, I am not looking for help implementing quicksort.
EDIT: To, hopefully, make the problem clearer here is what the implementation looks like:
# 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]