ruby - Array Alphabetical Sorting Without .sort -


i'm trying sort multiple strings alphabetical array without using .sort method. i've tried while loops, if statements, it's not working.

i keep getting nil error on line 13 when comparing user_input array. don't know how fix , don't understand why it's happening.

alpha_sorter = [' '] user_input = ' ' sort_counter = 0  puts 'type in many words want.' puts 'one word per line.' puts 'when done, leave line blank , 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 

my program using sort:

alpha_sorter = [] user_input = ' '   puts 'type in many words want.' puts 'one word per line.' puts 'when done, leave line blank , press enter.'  while (user_input != '')   user_input = gets.chomp   alpha_sorter.push user_input end  puts alpha_sorter.sort 

sorry if confused more, i'm trying newb.lol

here solution lots of notes explain:

puts puts "enter words , returned them in alphabetical order!" puts input = gets.chomp input = input.split   def swap(array)     =0   while < array.length #here 1 iteration on array      i2 = + 1     while i2 < array.length #here second. allows me compare second index (and rest i2 increments) current 1       if array[i] < array[i2]  #if second larger first         array[i]  , array[i2] = array[i2], array[i] #switch them. called parallel assignment       end # if       i2 += 1  #increment second loop before first. keep incrementing until end before first 1 does. whole thing starts again until first loop has reached full length of array     end # inner loop     += 1  end # outer loop   puts   puts '...and magic ...here string in alphabetical order!! :'   puts   return array.reverse.join(' ') end # def  puts swap(input) 

another nifty solution found on web (which mad didn't think of) :

def shuffle_sort(array) sorted = []   while !array.empty? #do until array empty     sorted << array.delete(array.min) #push word min value sorted delete it. min enum method   end                                return sorted.join(' ') end  puts shuffle_sort(alpha) 

now how beautiful that??! #min method returns object (a word in case) minimum value!! :)


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -