AHMED M A
2 min readMay 10, 2021

--

Merge sort by ruby language

Merge sort is a commonly used sorting algorithm in computer science. In Ruby, it can be implemented easily due to the simplicity of the language and its support for data structures and algorithms.

To explain merge sort in Ruby, we first check if the size of the array is equal to or less than one. If it is, we simply return the same array. Otherwise, we proceed to the next step.

In the second step, we divide the array into two halves: the left and the right. The left half consists of elements from index 0 to the middle of the array, while the right half consists of elements from the middle of the array to the end. We then recursively call the `sort_merge` function on the left and right arrays.

We continue this recursion until the size of the returned array is one or less. Once we have the left and right arrays, we pass them to another function called `merge`.

In the `merge` function, we compare the first element of the right array with the first element of the left array. If the first element of the right array is less than the first element of the left array, we add it to a new array. Otherwise, we add the left element to the new array.

Finally, at the end step, if there are any remaining elements in either the left or right array, we concatenate them with the new array.

This process is repeated by calling `merge` until all the recursion is completed.

--

--