Manav Dutta
Manav Dutta

Reputation: 171

System Stack Error

So I have the following code for a Merge Sort in Ruby.

class MergeSort

     def sort(array)
               if array.length == 1 || array.length == 0
                   return array
               end
               firstHalf = array[0..array.length / 2]
               secondHalf = array[(array.length / 2) + 1..array.length]
               firstHalf = sort(firstHalf)
               secondHalf = sort(secondHalf)
               b = 0
               c = 0
               for i in (0..(firstHalf.length - 1))
                  while b < secondHalf.length && firstHalf[i] >= secondHalf[b]
                       array[c] = secondHalf[b]
                       b = b + 1
                       c = c + 1
                  array[c] = firstHalf[i]
                  c = c + 1
               end
               return array
     end

end

array = [1,4,9,14,20,25]
puts MergeSort::new.sort(array)

When I run the code, I get a SystemStackError. Can someone tell me why this is happening? Thanks.

Upvotes: 0

Views: 55

Answers (2)

StuartLC
StuartLC

Reputation: 107277

At a guess, once the array length gets to 3 (i.e. elements [0..2]), the call

firstHalf = array[0..array.length / 2]

evaluates to

0..1.5 and if 1.5 is rounded up to 2

which then calls sort [0..2] again

and eventually you get a stack overflow?

Upvotes: 1

Severin
Severin

Reputation: 8588

In order to call .new you have to have an initialize method in your class. What you probably wanted to do was calling .sort on the class itself, in which case you have to prefix it with self, so:

class MergeSort
   def self.sort(array)
   ...

Afterwards you can call it like this:

MergeSort.sort(array)

Upvotes: 0

Related Questions