Implementing the merge sort algorithm
In this section, we are going to implement the merge sort algorithm. Though merge sort is a popular sorting method, it's not used as much as quick sort because it is slightly slower in real-world scenarios. However, I love merge sort because it is easy to understand from a high-level perspective. In terms of coding, it has a slightly longer code implementation than quick sort but is also easier to understand.
At a higher level, merge sort breaks down the entire array into smaller groups, sorts the values inside each subgroup, and merges it with the larger group to sort a collection.
To implement the algorithm, we are going to create two methods: one called merge
and the other called merge_sort
:
def merge_sort(list) end def merge(left, right) end
As the name suggests, merge
will take the right
and left
values and merge them together. We begin by writing the code inside our merge
method:
def merge(left, right) if left.empty? right elsif right.empty...