Monday, 15 March 2010

ruby - Array Alphabetical Sorting Without .sort -


I am trying to sort a string in an alphabetical array without using the .stort method. I have tried the loops, if statement, but it is not working

When I compare user_input in the array, I keep getting zero error on line 13. I do not know how to fix it and I do not even understand why this is happening.

  alpha_source = [''] user_input = '' sort key connect = 0 '' type a few words as you wish. ' 'Puts one word per line.' 'When you're done, leave the blank line and press enter.' While (user_input! = '') User_input = gets.chomp.downcase if (user_input & lt; = Alfa_sortr [sort_counter]) Alfa_srtrkinsrt (Sortkounccr, Ughr_input) sort_counter = 0 else sort_counter + = 1 end end puts Alfa_srtr  

Sort using my program: to

  Alfa_sotr = [] user_input = 'puts' type as you need many words. '' Puts one word per line. ' 'When you're done, leave the blank line and press enter.' While (user_input! = '') User_input = gets.chomp alpha_sorter.push puts alpha_sorter.sort in user_input end  

Sorry, if I put you in more confusion, then I'm just trying to help in another newb.lol

To illustrate here a lot of My solution was with notes:

  puts a few words to enter and I will return them in alphabetical order according to you! "Input = gets.chomp input = input.split def swap (array) i = 0 puts the i & lt; Array.length # The array is a walk on i2 = i + 1 while i2 & lt; Array.length # Here is a second, it allows me to compare the second one (as I2 increments in the form of the rest) to the current one if the array [i] & lt; array [i2] # if the second first array [ I] = array [i2], array [i] #switch them. This is called parallel assignment # if i2 + = 1 # before other loop first Hana. It is the first time to keep moving until finally the whole thing starts over again until that does not reach the full length of the end of the first loop array # puts inner loop i + = 1 end # Outer Loop ... and just like magic ... here is your string in alphabetical order !! "puts return array. Riwarskjoind ( '') and # def the swaps (input)  

Another nifty solution found on the web (I do not think I was crazy Defense is):

  Diif Sfl_sort (array) is sorted [=] while! Array.Activated? #do Unless the array is sorted empty & lt; & Lt; Array.delete (array.min) # Sort the word with the minimum value, then delete it. Minute an enum method ending sorted.join ('') puts the end shuffle_sort (alpha)  

Now how beautiful is it ?? The #min object (one word in this case) returns with minimal value !! :)


No comments:

Post a Comment