Last active
April 12, 2019 18:18
-
-
Save omedale/ae9fff4c7c1c79b25c08b136feacf5c9 to your computer and use it in GitHub Desktop.
Ruby Implementation of Merge Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def merge_sort(array) | |
| # set base case to allows the recursion to work and not go on indefinitely. | |
| return array if array.size <= 1 | |
| # split the array into two | |
| left, right = array.each_slice((array.size/2).round).to_a | |
| # merge the mergesorted left half with the mergesorted right half. | |
| merge = -> (left, right) { | |
| array = [] | |
| while left.size > 0 && right.size > 0 | |
| array << (left[0] < right[0] ? left.shift : right.shift) | |
| end | |
| return array + left + right | |
| } | |
| return merge.call merge_sort(left), merge_sort(right) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment