阵列按字母排序没有.sort

时间:2015-03-17 06:20:59

标签: ruby arrays sorting

我正在尝试将多个字符串排序为字母数组,而不使用.sort方法。我试过while循环,如果语句,但它不起作用。

在将user_input与数组进行比较时,我在第13行继续收到nil错误。我不知道如何解决这个问题,我甚至不明白为什么会发生这种情况。

alpha_sorter = [' ']
user_input = ' '
sort_counter = 0

puts 'Type in as many words as you want.'
puts 'One word per line.'
puts 'When you are done, leave the line blank and press enter.'

while (user_input != '')
  user_input = gets.chomp.downcase
  if (user_input <= alpha_sorter[sort_counter])
    alpha_sorter.insert(sort_counter, user_input)
    sort_counter = 0
  else
    sort_counter += 1
  end
end

puts alpha_sorter

我的程序使用sort:

alpha_sorter = []
user_input = ' '


puts 'Type in as many words as you want.'
puts 'One word per line.'
puts 'When you are done, leave the line blank and press enter.'

while (user_input != '')
  user_input = gets.chomp
  alpha_sorter.push user_input
end

puts alpha_sorter.sort

2 个答案:

答案 0 :(得分:1)

对不起,如果我更加困惑你,我只是想帮助另一个newb.lol

这是我的解决方案,有许多解释说明:

puts
puts "Enter some words and I will returned them to you in alphabetical order!"
puts
input = gets.chomp
input = input.split


def swap(array)  
  i =0
  while i < array.length #here is one iteration over the array

    i2 = i + 1
    while i2 < array.length #here is a second. this allows me to compare the second index (and the rest as i2 increments) to the current one
      if array[i] < array[i2]  #if the second is larger than the first
        array[i]  , array[i2] = array[i2], array[i] #switch them. this is called parallel assignment
      end # if
      i2 += 1  #increment the second loop before the first. it will keep incrementing until the end before the first one does. then the whole thing starts again until the first loop has reached the full length of the array
    end # inner loop
    i += 1
 end # outer loop
  puts
  puts '...And just like magic ...here is your string in alphabetical order!! :'
  puts
  return array.reverse.join(' ')
end # def

puts swap(input)

我在网上发现的另一个漂亮的解决方案(我生气,我没想到)是:

def shuffle_sort(array)
sorted = []
  while !array.empty? #do this until the array is empty
    sorted << array.delete(array.min) #push the word with the min value into sorted then delete it. min is a enum method
  end                             
  return sorted.join(' ')
end

puts shuffle_sort(alpha)

现在多么美丽??! #min方法返回最小值的对象(在本例中为单词)! :)

答案 1 :(得分:0)

Ruby中的快速排序非常简单:

def sort(arr)
  return [] unless arr
  pivot = arr[0]
  grouped = arr.group_by { |e| e <=> pivot }
  sort(grouped[-1]) + grouped[0] + sort(grouped[1])
end

这是天真的方法,但应该有用。