Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a merge sort?

Tags:

ruby

mergesort

I am trying to implement a merge sort and am getting stack level too deep (SystemStackError) error when I run my code. I am not sure what the issue may be.

def merge_sort(lists)
  lists if lists.count == 1

  middle  = lists[0..(lists.count / 2) - 1 ]
  left = lists[0..middle.count - 1]
  right = lists[middle.count..lists.count]

  x = merge_sort(left)
  y = merge_sort(right)
end

merge_sort [1,2,3,4,5,6,7,8]

Any help would be great!

like image 311
user2985306 Avatar asked Jan 14 '14 18:01

user2985306


People also ask

How do you create a merge sort?

Algorithm for Merge SortStep 1: Find the middle index of the array. Step 2: Divide the array from the middle. Step 4: Call merge sort for the second half of the array. Step 5: Merge the two sorted halves into a single sorted array.

How do you explain merge sort?

In the context of sorting elements in a list and in ascending order, the merge sort method divides the list into halves, then iterates through the new halves, continually dividing them down further to their smaller parts.


2 Answers

From wikipedia:

def mergesort(list)
  return list if list.size <= 1
  mid   = list.size / 2
  left  = list[0...mid]
  right = list[mid...list.size]
  merge(mergesort(left), mergesort(right))
end

def merge(left, right)
  sorted = []
  until left.empty? || right.empty?
    if left.first <= right.first
      sorted << left.shift
    else
      sorted << right.shift
    end
  end
  sorted.concat(left).concat(right)
end
like image 81
max Avatar answered Sep 19 '22 13:09

max


write this

 return lists if lists.count == 1

instead of

 lists if lists.count == 1

In Ruby, from a method last statement is always returned by default. But if you want to return from the middle of any lines except the last line conditionally, you must need to use return keyword explicitly.

like image 33
Arup Rakshit Avatar answered Sep 17 '22 13:09

Arup Rakshit