Merge Sort in Ruby
Welcome to Merge Sort
Welcome, aspiring programmer! Today's topic is Merge Sort. Merge Sort is a sorting technique reminiscent of organizing a shuffled deck of cards in order. For large-scale data, Merge Sort can outperform typical techniques. Today, we'll explore Merge Sort, code it in Ruby, and analyze its efficiency. Ready? Let's get started!
What is Merge Sort?
In computer science, Merge Sort is a popular method to sort elements. Merge Sort uses the 'divide-and-conquer' strategy similar to the Quick Sort algorithm. The three main steps of Merge Sort are:
- Split the array into halves.
- Sort each half separately.
- Merge the sorted halves back together.
Understanding the Merge Process
We will begin by building code for merging two sorted parts. The merge process involves comparing elements from two halves and merging them so the resulting list is sorted.
Let's code a merge function in Ruby to achieve this. We will make use of Ruby's Array operations and slice capabilities.
Here, we've divided our original list into two halves, left_array and right_array.
Merging the Halves Back Together
Now, we'll sort and merge these halves:
This code places two pointers, i and j, at the beginning of the left_array and right_array. It selects the smaller element, places it in the final array arr, and moves the corresponding pointer onward. This continues until all elements are merged.
Once one of the pointers reaches the end of its array, some elements might be left in the other array. To handle this, let's copy the remaining elements of both arrays (if any) to the end of the resulting arr array.
