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

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

Nim Merge Sort with Detailed Helper Functions

Nim

Goal -- WPM

Ready
Exercise Algorithm Area
1proc mergeSort(arr: var seq[int]) =
2# Sorts a sequence of integers in ascending order using the Merge Sort algorithm.
3# This is the main entry point for the sorting process.
4
5if arr.len <= 1:
6# Base case: A sequence with 0 or 1 element is already sorted.
7return
8
9# Create a temporary buffer for merging. This is allocated once.
10# It's more efficient than allocating in each merge call.
11var tempBuffer = newSeq[int](arr.len)
12
13# Call the recursive helper function to perform the sort.
14mergeSortRecursive(arr, tempBuffer, 0, arr.len - 1)
15
16
17proc mergeSortRecursive(arr: var seq[int], temp: var seq[int], left: int, right: int) =
18# Recursively divides the array and calls merge.
19# `left` and `right` define the current subarray boundaries.
20
21if left < right:
22# Find the middle point to divide the array into two halves.
23let mid = left + (right - left) div 2
24
25# Recursively sort the first half.
26mergeSortRecursive(arr, temp, left, mid)
27
28# Recursively sort the second half.
29mergeSortRecursive(arr, temp, mid + 1, right)
30
31# Merge the sorted halves.
32merge(arr, temp, left, mid, right)
33
34
35proc merge(arr: var seq[int], temp: var seq[int], left: int, mid: int, right: int) =
36# Merges two sorted subarrays arr[left..mid] and arr[mid+1..right].
37# Uses `temp` array for intermediate storage.
38
39var i = left # Initial index for the first subarray.
40var j = mid + 1 # Initial index for the second subarray.
41var k = left # Initial index for the merged subarray (in `temp`).
42
43# Copy data to temporary buffer `temp` to facilitate merging back into `arr`.
44# This is a common optimization to avoid repeated allocations.
45for idx in left..right:
46temp[idx] = arr[idx]
47
48# Merge the two halves back into the original array `arr`.
49while i <= mid and j <= right:
50if temp[i] <= temp[j]:
51arr[k] = temp[i]
52inc i
53else:
54arr[k] = temp[j]
55inc j
56inc k
57
58# Copy the remaining elements of the first half, if any.
59while i <= mid:
60arr[k] = temp[i]
61inc i
62inc k
63
64# The second half's remaining elements are already in place in `temp`
65# and will be copied over if `j` is still within bounds.
66# However, since `temp` is a copy of `arr`'s relevant section,
67# and we are merging *into* `arr`, if `j` has remaining elements,
68# they are already in `arr`'s `temp` buffer and will be correctly placed.
69# The loop `while j <= right` is implicitly handled by the initial copy
70# and the fact that `k` will eventually reach `right + 1`.
71
72
73# Example Usage:
74var numbers = @[12, 11, 13, 5, 6, 7]
75let n = numbers.len
76
77if n > 0:
78echo "Original array: " & $numbers
79mergeSort(numbers)
80echo "Sorted array: " & $numbers
81else:
82echo "Array is empty, nothing to sort."
83
84var singleElement = @[42]
85mergeSort(singleElement)
86echo "Sorted single element array: " & $singleElement
87
88var emptyArray: seq[int] = @[]
89mergeSort(emptyArray)
90echo "Sorted empty array: " & $emptyArray
Algorithm description viewbox

Nim Merge Sort with Detailed Helper Functions

Algorithm description:

This Nim code implements the Merge Sort algorithm, a highly efficient, comparison-based sorting technique. It recursively divides the input sequence into smaller halves, sorts them, and then merges the sorted halves. This approach is stable and guarantees O(n log n) time complexity. Merge Sort is widely used in various applications requiring reliable sorting, such as in database systems and file sorting utilities.

Algorithm explanation:

Merge Sort is a divide-and-conquer algorithm. It works by recursively breaking down the array into halves until each subarray contains only one element (which is considered sorted). Then, it repeatedly merges these subarrays to produce new sorted subarrays until there is only one sorted array remaining. The `mergeSortRecursive` function handles the division, and the `merge` function combines two sorted subarrays. The time complexity is O(n log n) in all cases (best, average, and worst) because the dividing and merging steps always take the same amount of time. The space complexity is O(n) due to the auxiliary space required for the temporary buffer used during the merge operation. Edge cases like empty arrays or arrays with a single element are handled by the base case condition `arr.len <= 1`.

Pseudocode:

function mergeSort(array):
  if array.length <= 1:
    return
  create tempBuffer of same size as array
  call mergeSortRecursive(array, tempBuffer, 0, array.length - 1)

function mergeSortRecursive(array, temp, left, right):
  if left < right:
    mid = left + (right - left) / 2
    mergeSortRecursive(array, temp, left, mid)
    mergeSortRecursive(array, temp, mid + 1, right)
    call merge(array, temp, left, mid, right)

function merge(array, temp, left, mid, right):
  copy elements from array[left..right] to temp[left..right]
  i = left, j = mid + 1, k = left
  while i <= mid and j <= right:
    if temp[i] <= temp[j]:
      array[k] = temp[i]
      increment i
    else:
      array[k] = temp[j]
      increment j
    increment k
  while i <= mid:
    array[k] = temp[i]
    increment i
    increment k