ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Ruby Merge Sort Implementation

Ruby

Goal -- WPM

Ready
Exercise Algorithm Area
1def merge_sort(arr)
2# Base case: if the array has 0 or 1 element, it's already sorted.
3return arr if arr.nil? || arr.length <= 1
4
5# Find the middle point to divide the array into two halves.
6mid = arr.length / 2
7
8# Recursively sort the left and right halves.
9left_half = merge_sort(arr[0...mid])
10right_half = merge_sort(arr[mid..-1])
11
12# Merge the sorted halves.
13merge(left_half, right_half)
14end
15
16def merge(left, right)
17# Initialize an empty array to store the merged result.
18merged = []
19i = 0 # Pointer for the left array
20j = 0 # Pointer for the right array
21
22# Compare elements from both arrays and add the smaller one to merged.
23while i < left.length && j < right.length
24if left[i] <= right[j]
25merged << left[i]
26i += 1
27else
28merged << right[j]
29j += 1
30end
31end
32
33# Append any remaining elements from the left array.
34while i < left.length
35merged << left[i]
36i += 1
37end
38
39# Append any remaining elements from the right array.
40while j < right.length
41merged << right[j]
42j += 1
43end
44
45merged
46end
47
48def merge_sort_with_duplicates(arr)
49# A version that explicitly handles duplicates and maintains stability.
50# The core logic remains the same as merge_sort.
51merge_sort(arr)
52end
Algorithm description viewbox

Ruby Merge Sort Implementation

Algorithm description:

This Ruby code implements the merge sort algorithm, a highly efficient, comparison-based sorting algorithm. It works by recursively dividing an array into smaller subarrays until each subarray contains only one element (which is trivially sorted). Then, it repeatedly merges these sorted subarrays to produce new sorted subarrays until there is only one sorted array remaining. This algorithm is stable and has a predictable performance.

Algorithm explanation:

Merge sort is a divide-and-conquer algorithm. The `merge_sort` function first checks for the base case: an array with 0 or 1 element is already sorted. Otherwise, it divides the array into two halves, recursively calls `merge_sort` on each half, and then uses the `merge` helper function to combine the two sorted halves into a single sorted array. The `merge` function takes two sorted arrays, `left` and `right`, and iterates through them, comparing elements and adding the smaller one to a `merged` array. Any remaining elements from either array are appended. The time complexity of merge sort is O(n log n) in all cases (best, average, and worst) because the array is consistently divided and merged. The space complexity is O(n) due to the auxiliary space required for the `merged` array during the merge step. This algorithm is stable, meaning that elements with equal values maintain their relative order in the sorted output.

Pseudocode:

function merge_sort(array):
  if array length <= 1:
    return array
  find middle index
  split array into left and right halves
  sorted_left = merge_sort(left half)
  sorted_right = merge_sort(right half)
  return merge(sorted_left, sorted_right)

function merge(left_array, right_array):
  initialize empty merged_array
  initialize pointers i=0 for left, j=0 for right
  while i < left_array.length and j < right_array.length:
    if left_array[i] <= right_array[j]:
      add left_array[i] to merged_array
      increment i
    else:
      add right_array[j] to merged_array
      increment j
  add remaining elements from left_array to merged_array
  add remaining elements from right_array to merged_array
  return merged_array