我正在尝试为选择排序编写代码。到目前为止,它已部分运作。我不知道为什么第一个循环没有进入内循环,但随后的循环似乎是这样。
我的代码是:
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]
注意第一行和第二行。在第一行之后,循环应进入内循环,输出&#34; ...现在xxx&#34;,而是进入下一步。
答案 0 :(得分:1)
while z >= 0 and z < y
应该是
while z >= 0 and z <= y
由于此时此z
和y
都设置为0。