bisuke - 10 months ago 37

Ruby Question

I would really appreciate it if someone can help me on this.

I want to input numbers on this array x[0,100]

Then, print the whole array but with the numbers inside sorted from the smallest to biggest WITHOUT using sort array.

I have this code so far, but I get an error where I do the comparison. Can someone help me on this please?

`x = [0,100]`

print x

puts "\nInput any number from 0~100"

num = gets.to_i

x.push(num)

for i in 0..x.length-1

for j in 0..x.length-1

if x[j] < x[j+1]

swap = x[j]

x[j] = x[j+1]

x[j+1] = swap

end

end

end

p x

Answer

Regardless of what the best solution would be, you get an error because your second loop is going out of bound: you're calling x[j+1] up to x.length-1, which means that you end up calling x[x.length] when the last element is x[x.length - 1].

Just replace "for j in 0..x.length-1" with "for j in 0..x.length-2"

```
x = [0,100]
print x
puts "\nInput any number from 0~100"
num = gets.to_i
x.push(num)
for i in 0..x.length-1
for j in 0..x.length-2
if x[j] < x[j+1]
swap = x[j]
x[j] = x[j+1]
x[j+1] = swap
end
end
end
p x
```