Browse files

Add implementation for merge sort in ruby

  • Loading branch information...
1 parent fc489e6 commit 403592a9a15dcb1c3123dfae419c88f85f7999c1 @neilparikh committed Jan 3, 2013
Showing with 34 additions and 0 deletions.
  1. +34 −0 merge_sort.rb
View
34 merge_sort.rb
@@ -0,0 +1,34 @@
+def mergeSort(array)
+ if array.length < 2
+ return array
+ else
+ mid = (array.length-1)/2
+ left = mergeSort(array[0..mid])
+ right = mergeSort(array[(mid+1)..(array.length-1)])
+ return merge(left, right)
+ end
+end
+
+def merge(a, b)
+ final = []
+ while a.length != 0 and b.length != 0
+ if a[0] < b[0]
+ # First element of a is smaller, so add that to the final array,
+ # and remove it from array a.
+ final << a.shift
+ else
+ # First element of b is smaller, so add that to the final array,
+ # and remove it from array b.
+ final << b.shift
+ end
+ end
+
+ # When only one array has elements, just append them all to the end,
+ # Since that array is also sorted.
+ (a + b).each do |element|
+ final << element
+ end
+ return final
+end
+
+p mergeSort([4, 2, 3, 1, 5, 9, 8, 7, 6])

0 comments on commit 403592a

Please sign in to comment.