I am trying to write a code for a selection sort. So far it's partially working. I don't know why the first loop didn't enter the inner loop, but the subsequent loops seem to so.
My code is:
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}"
And the result is:
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]
Notice the first line and second lines. After the first line the loop should enter the inner loop, outputting "...now xxx", but instead it went to the next step.
while z >= 0 and z < y
should be
while z >= 0 and z <= y
Since z
and y
, at that moment, are both currently set to 0.