2015-10-08 124 views
0

我正在嘗試爲選擇排序編寫代碼。到目前爲止,這部分工作。我不知道爲什麼第一個循環沒有進入內部循環,但後來的循環似乎如此。While循環選擇排序

我的代碼是:

x = [2,3,1,5,8,6] 
y = 0 
z = 0 
while y >= 0 and y < x.count 
    puts "now y is #{y}, and z is #{z} " 
    while z >= 0 and z < y 
    puts "...now y is #{y}, and z is #{z} " 
    if x[y] < x[z] 
     x.insert(y-1, x[y]) 
     x.delete_at(y+1) 
    puts "new array is #{x}" 
    else 
    puts "still old array #{x}" 
    end 
    z += 1 
    end 

y += 1 
end 

puts "the final is #{x}" 

,其結果是:

now y is 0, and z is 0 
now y is 1, and z is 0 
...now y is 1, and z is 0 
still old array [2, 3, 1, 5, 8, 6] 
now y is 2, and z is 1 
...now y is 2, and z is 1 
new array is [2, 1, 3, 5, 8, 6] 
now y is 3, and z is 2 
...now y is 3, and z is 2 
still old array [2, 1, 3, 5, 8, 6] 
now y is 4, and z is 3 
...now y is 4, and z is 3 
still old array [2, 1, 3, 5, 8, 6] 
now y is 5, and z is 4 
...now y is 5, and z is 4 
new array is [2, 1, 3, 5, 6, 8] 
the final is [2, 1, 3, 5, 6, 8] 

通知所述第一線和第二線。在第一行之後,循環應該進入內部循環,輸出「... now xxx」,但是轉到下一步。

+1

獲取做出的習慣,確定你的縮進是當前和正確的。我們使用縮進來查看塊/循環中發生了什麼,並且可以更快地診斷代碼過早結束的情況。 –

+0

感謝您的提示,@theTinMan :) – ray

回答

1
while z >= 0 and z < y 

應該

while z >= 0 and z <= y 

由於zy,在那一刻,都是當前設置爲0。

+0

啊...是的,@ philip-yoo,謝謝!!!這是一個愚蠢的錯誤...大聲笑 – ray

+0

沒有問題:)它發生了 –