Tutorijal Sortiranje Brojeva - Ruby

  • Začetnik teme Začetnik teme lnxdr
  • Datum pokretanja Datum pokretanja

lnxdr

Obećava
Poruka
68
Videh slicnu temu pa cu ovde postavljati Ruby kod za razlicite manipulacije brojevima. Posto ce isteci vreme za izmenu glavnog posta, dodavacu nakon ovog, u spojlerima kod za manipulaciju brojevima u Ruby jeziku.

Ruby:
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

KAKO KORISTITI:

Ruby:
  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}"

Ruby:
module FisherYates

  def self.shuffle(numbers)
    n = numbers.length
    while n > 0
      x = rand(n-=1)
      numbers[x], numbers[n] = numbers[n], numbers[x]
    end
    return numbers
  end

end

KAKO KORISTITI:

Ruby:
  @numbers = [1,2,3,4,5,6,7,8,9,10,12,13,14]

  puts FisherYates.shuffle(@numbers).inspect

Ruby:
module Bubble

  def self.sort(array)

    n = array.length

    loop do
      swapped = false
      (n-1).times { |i| if array[i] > array[i+1]
          array[i], array[i+1] = array[i+1], array[i]
          swapped = true
        end }
      break if not swapped
    end

    array
  end

KAKO KORISTITI:

Ruby:
  @numbers = [13, 154, 22, 139, 144]

  puts Bubble.sort(@numbers)
 
Poslednja izmena:

Back
Top