Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
Basic Implementation
basic.rb
def merge_sort(values)
return values if values.length <= 1
mid = values.length / 2
left = merge_sort(values[0...mid])
right = merge_sort(values[mid..])
merged = []
i = 0
j = 0
while i < left.length && j < right.length
if left[i] <= right[j]
merged << left[i]
i += 1
else
merged << right[j]
j += 1
end
end
merged + left[i..] + right[j..]
end
arr = [5, 1, 4, 2, 8]
puts merge_sort(arr).inspect
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
merge_sort(values)is a Ruby method that returns an array; it does not mutate the originalarr.- The base case is
return values if values.length <= 1, so one-element slices are returned directly. mid = values.length / 2uses integer division, thenvalues[0...mid]andvalues[mid..]create the left and right slices for recursive calls.merged = []collects the merged result, withiandjtracking current positions in the sortedleftandrightarrays.- The comparison uses
left[i] <= right[j], so equal values would keep the left value first. merged << left[i]andmerged << right[j]append values; leftover tails are joined withmerged + left[i..] + right[j..].- The trace shows the pinned input splitting into
[5, 1]and[4, 2, 8], then returning sorted halves[1, 5]and[2, 4, 8]. - The final merge returns
[1, 2, 4, 5, 8], andputs merge_sort(arr).inspectprints that Ruby array representation.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.