Created
April 17, 2024 14:43
-
-
Save utkarshsingh99/a543f98b57c59d3059c96e1823c846b9 to your computer and use it in GitHub Desktop.
This file contains 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
proc mergeSort[T](arr: var seq[T]) = | |
# Check if the array has more than one element | |
if arr.len <= 1: | |
return | |
# Calculate mid index | |
let mid = arr.len div 2 | |
# Split the array into two halves | |
var leftHalf = arr[0 ..< mid] | |
var rightHalf = arr[mid ..< arr.len] | |
# Recursively sort the two halves | |
mergeSort(leftHalf) | |
mergeSort(rightHalf) | |
# Merge the sorted halves | |
var i = 0 | |
var j = 0 | |
var k = 0 | |
while i < leftHalf.len and j < rightHalf.len: | |
if leftHalf[i] <= rightHalf[j]: | |
arr[k] = leftHalf[i] | |
inc(i) | |
else: | |
arr[k] = rightHalf[j] | |
inc(j) | |
inc(k) | |
# Copy the remaining elements of leftHalf, if any | |
while i < leftHalf.len: | |
arr[k] = leftHalf[i] | |
inc(i) | |
inc(k) | |
# Copy the remaining elements of rightHalf, if any | |
while j < rightHalf.len: | |
arr[k] = rightHalf[j] | |
inc(j) | |
inc(k) | |
# Example script | |
var nums = @[38, 27, 43, 3, 9, 82, 10] | |
echo "Original array:", nums | |
mergeSort(nums) | |
echo "Sorted array:", nums |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment