I created the following code to do the bubble sort and the code worked out fine. My question is why it worked... When the method is called, I assume the computer will first evaluate whether $x is equal to 0. But I haven't assigned value to $x to begin with, so what makes the computer start to run the each loop?
It seems to have something to do with the fact that x is a global variable, but I am not sure how. Please suggest!
while $x != 0
$x = 0
arr.each_with_index do |i, j|
if arr[j+1] != nil && i > arr[j+1]
arr[j], arr[j+1] = arr[j+1], arr[j]
$x += 1
I assume you're invoking the method only once? ...
The global $x doesn't exist during the first call and the search for that global variable returns
Hence, the first
while loop evaluates
nil == 0 which is