DEV Community

Linuxander
Linuxander

Posted on

How to sort numbers in ruby

This is a simple module to sort numbers from lower to higher:

module Sort

  def numbers(array)
    n = array.length - 1
    x = 0
    while x <= n - 1
      first = x
      y = x + 1
      while y <= n
        first = y if array[y] < array[first]
        y += 1
      end
      array[x], array[first] = array[first], array[x] unless x = first
      x += 1
    end
  end

end
Enter fullscreen mode Exit fullscreen mode

Now you can use this module like this:

  nums = [14,2,290,13,54,254,66,72,918,90]

  puts "Numbers to sort: #{nums}"

  data = Sort.numbers(nums)
  puts "Sorted numbers: #{data.inspect}"

  x_data = data.shuffle
  puts "Shuffled numbers: #{x_data.inspect}"

  y_data = Sort.numbers(x_data)
  puts "Sorted again: #{y_data.inspect}"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)