选择排序的while循环

While loop for selection sort

我正在尝试为选择排序编写代码。到目前为止,它部分工作。不知道为什么第一个循环没有进入内层循环,后面的循环好像都是。

我的代码是:

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”,但它却进入了下一步。

while z >= 0 and z < y

应该是

while z >= 0 and z <= y

因为 zy,在那一刻,当前都设置为 0。