I wrote merge sort in Ruby
I am learning sorting algorithms these days. And to me merge sort looks simple than other sorts. (There are merge sort, insertion sort, quick sort, selection sort, bubble sort, et cetera.)
I thought I should try to write it in Ruby.
The steps of the merge sort are:
- First, split the array (yes, I’m sorting an array of numbers) into two halves.
- Second, sort those two arrays.
- And then, merge the two sorted arrays and update original array, in the order of “small number first”. (yes, I’m sorting it in ascending order)
As always, I am writing a test first (lol) because I like to see some tests are passing.
class Sorter def self.merge_sort(array) array.sort # make the test pass end end require "minitest/autorun" class SorterTest < Minitest::Test def test_merge_sort array = [2, 1, 3] assert_equal [1, 2, 3], Sorter.merge_sort(array) end end
I am going to name the...
Continue reading →