Search code examples
rubyalgorithmmergesort

Merge Sort confusion, stack level too deep?


So Im learning merge sort (In Ruby) and I understand mostly of how it works, so I was just writing the beginning of the "mergeSort" functionality and splitting the arrays up:

array = [5,1,8,3,4,6,11,2]

def mergeSort(arr,beginIndex,endIndex)
  if endIndex > beginIndex
    mid = (beginIndex+endIndex)/2 
    puts mid
    puts "#{arr[0..mid]}"
    puts "#{arr[mid+1..-1]}"
    mergeSort(arr,0,mid) #comment out here?
    mergeSort(arr,mid+1,arr.length-1) #or here?

  end


end
mergeSort(array,0,array.length-1)

So I understand whats happening, and whats printing out works correctly. However the strange thing is...if I comment out either one of the secondary nested mergeSort's (where I say "#comment out here? or here?) I get a printout like I would think. However if I leave both it'll go on forever until I get a "stack level too deep". Which is weird because commenting out either one it'll stop when the array is at 1 length.

Why is this happening?


Solution

  • The second call should be mergeSort(arr,mid+1,endIndex).

    It works fine if you leave out the second call because you narrow in to the beginning. It works fine if you leave out the first call because you narrow in to the end. It fails if you have both because you go to sort the first half and find yourself on the second call still trying to sort the whole array...recursively.