2016-11-05 109 views
0

我想弄清楚爲什麼這個交換不能正常工作。我添加p以覈實repl.it這是一個快速排序分區方法的值:Ruby變量交換混淆

def partition (array, from, to) 
    #declared pivot to last index of array 
    pivot = array[to] 
    pIndex = from 
    for i in from..to-1 
     if array[i] <= pivot 
      array[i], array[pIndex] = array[pIndex], array[i] 
      pIndex += 1 
     end 
    end 
    p pivot 
    p array[to] 
    ### why doesn't this work properly? pivot is same as array[to] 
    ### array[pIndex], pivot = pivot, array[pIndex] 
    ### the swap below works 
    array[pIndex], array[to] = array[to], array[pIndex] 
    p array 
    return pIndex 
end 

我有pivot = array[to]。然後它與數組[pIndex]交換:array[pIndex], pivot = pivot, array[pIndex]array[pIndex]值更改爲pivot,但pivot未更改爲array[pIndex]。但是,當我這樣做,而不是:array[pIndex], array[to] = array[to], array[pIndex]它完美找到。誰能告訴我爲什麼?

實施例以與陣列:

arr = [7, 2, 1, 6, 8, 5, 3, 4]

partition(arr, 0,7)

最後交換之前發生陣列是[2, 1, 3, 6, 8, 5, 7, 4]。我的最後一個交換行是假設交換pivot這是4,array[pIndex]這是6。這應該將數組更改爲[2, 1, 3, 4, 8, 5, 7, 6]

+0

在Ruby代碼中看到'for'是非常不尋常的。 '(從...到)每個都是更典型的Ruby。 – tadman

回答

0

我們來分析一下平行分配在這裏做什麼。

假設我們有一個數組:

arr = [1, 2] 
arr[0], arr[1] = arr[1], arr[0] 
# arr => [2, 1] 

這是預期的行爲 - 我們同時做了以下兩個操作:
arr[0] = arr[1]arr[1] = arr[0]

現在假設我們做

arr = [1, 2] 
first = arr[0] 
first, arr[1] = arr[1], first 
# arr => [1, 1] 
# first => 2 

這是因爲我們現在正在做的first = arr[1]arr[1] = first
first是設置爲在arr[0]處找到的值的變量,並且更改此變量不會突變該數組。

+1

smh一刻在那裏...大聲笑。那麼,我還處於學習階段!感謝您清除@Damon – hockmode

+0

@hockmode np,每個人在每個技能水平上都有這些時刻:) – Damon