bisuke - 2 years ago 91

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**