Search code examples
rubyarrayswhile-loopundefinedbubble-sort

Bubble Sort - Ruby undefined local variable or method


So I decided to write a program that bubble_sorts an array. It takes the first two elements of an array, and if the first one is smaller than the second one, it sorts them. It then moves on to the next two elements at positions 1 and 2, and sorts them.

Here is my code

num_array = [4,7,19,5,71,26,37,52,59,3]

def sort_array
  x = 0
  while num_array.find_index (x) < num_array.count
    if num_array[x] < num_array[x+1]
      num_array[x] = num_array[x]
    else
      num_array[x] = num_array[x+1]
    end
  x += 1
  end
end

I received the following error message.

NameError: undefined local variable or method 'num_array' for main: Object

I don't understand that, I clearly defined the variable num_array in my first line.

I could have easily sorted the array by using

num_array.sort

But I would like to sort it using the Bubble Sort method.

Help will be appreciated.


Solution

  • The num_array is out of scope. You should make it global variable $num_array or pass as parameter to sort_array. The last one is better.

    def sort_array!(num_array)
      x = 0
      while num_array[x] < num_array.count
        if num_array[x] < num_array[x+1]
          num_array[x] = num_array[x]
        else
          num_array[x] = num_array[x+1]
        end
        x += 1
      end
    
      num_array
    end
    
    num_array = [4,7,19,5,71,26,37,52,59,3]
    
    puts sort_array!(num_array)