Trying to write a sorting program with ruby - stack level too deep (system stack error) -


i'm reading chris pine's book "learn progam" (it's ruby). right i'm trying write program sorts words. unfortunately i'm stuck with: stack level deep (system stack error) in line 16, which, if googled correctly means there infinite loop, don't know why.

here's code:

words = [] wordss = [] word = 'word' = 0 k = 0  def sortw array   = 0   if    (array.length == 1) || (array.length == 0)   else sort array, [], [],   end   return array end  def sort unsorted, unsort, sorted,   k = 0 # error should here, according command prompt   while < unsorted.length      while (unsorted[i] < unsorted[k])       if    k < unsorted.length         k = k + 1       elsif k == unsorted.length         sorted.push unsorted[i]       else unsort.push unsorted[i]       end     end      = + 1     sort unsorted, unsort, sorted,   end    if unsort.length != 1     = 0     sort unsort, [], sorted,   else sorted.push unsort[0]   end    return sorted end  puts 'type 1 word per line...' puts 'typing enter on empty line sorts inputted words'  while word != ''   word = gets.chomp   words = words.push word end  wordss = (sortw words)  puts 'your words' puts words puts 'sorted here' puts wordss 

you getting error because recursion not stop due problem sorting algorithm. in sort method, k less unsorted.length. causes other arrays, sorted , unsort never populate.

for example try these input:

  • dog
  • zebra
  • cat

additionally, think want not include blank line change code from:

words = words.push word words = words.push word if word != ''

this creates unsorted array:

  • [0] dog
  • [1] zebra
  • [2] cat

numbered below iterations of recursive sort method.

#initial variable state: = 0 k = 1 
  1. dog = dog
    • skip second while loop
    • i = 1
  2. zebra > dog
    • skip second while loop
    • i = 2
  3. cat < dog
    • enter second while loop
      • k = 1, cat < zebra, keep looping
      • k = 2, cat = cat, exit while
    • i = 3
  4. since i equal unsorted array length, 2 while loops never entered anymore.

therefore, following code results in infinite loop since nothing pushed unsort array:

if unsort.length != 1   = 0   sort unsort, [], sorted, #problem `unsort` , `sorted` empty elsif ... end 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -