Código Ruby – Ordenamiento Radix

El código realiza un Ordenamiento de datos numéricos haciendo uso del Método Radix en Ruby:

def conteo(arr, exp)
  n = arr.length
  output = Array.new(n)
  count = Array.new(10, 0)

  for i in 0...n
    index = (arr[i] / exp) % 10
    count[index] += 1
  end

  for i in 1...10
    count[i] += count[i - 1]
  end

  i = n - 1
  while i >= 0
    index = (arr[i] / exp) % 10
    output[count[index] - 1] = arr[i]
    count[index] -= 1
    i -= 1
  end

  for i in 0...n
    arr[i] = output[i]
  end
end

def ordenamiento_radix(arr)
  max_value = arr.max
  exp = 1

  while max_value / exp > 0
    conteo(arr, exp)
    exp *= 10
  end
end

arr = [170, 45, 75, 90, 802, 24, 2, 66]
ordenamiento_radix(arr)
puts "Arreglo ordenado: #{arr}"

Deja un comentario