【问题标题】:While loop for selection sort选择排序的while循环
【发布时间】:2015-10-09 00:39:24
【问题描述】:

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

我的代码是:

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”,而是进入下一步。

【问题讨论】:

  • 养成确保缩进是最新且正确的习惯。我们使用缩进来查看块/循环中发生了什么,并且还可以更快地诊断代码何时过早结束。
  • 感谢您的提示,@theTinMan :)

标签: ruby selection-sort


【解决方案1】:
while z >= 0 and z < y

应该是

while z >= 0 and z <= y

由于 zy 在那个时候,当前都设置为 0。

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2018-10-04
    • 2012-08-20
    • 2018-09-19
    • 2017-01-07
    • 2016-03-18
    • 2019-04-18
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多