Created
July 31, 2022 14:03
-
-
Save cy6erGn0m/75f8ff2b5ae8c3a839c4747f9fbde21d to your computer and use it in GitHub Desktop.
Simple non-recursive merge sort implementation in Kotlin
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
fun <T : Comparable<T>> mergeSort(input: Array<T>) { | |
mergeSort(input, naturalOrder()) | |
} | |
fun <T> mergeSort(input: Array<T>, comparator: Comparator<T>) { | |
if (input.size < 2) return | |
val tempSpace = input.copyOf() | |
for (windowSize in generateSequence(1) { it * 2 }.takeWhile { it < input.size }) { | |
for (segment in 0 until input.size / windowSize step 2) { | |
val leftStart = segment * windowSize | |
val leftEnd = (leftStart + windowSize).coerceAtMost(input.size) | |
val rightStart = leftEnd | |
val rightEnd = (rightStart + windowSize).coerceAtMost(input.size) | |
if (rightStart == rightEnd) break | |
var leftIndex = leftStart | |
var rightIndex = rightStart | |
var resultIndex = 0 | |
while (leftIndex < leftEnd && rightIndex < rightEnd) { | |
val comparisonResult = comparator.compare(input[leftIndex], input[rightIndex]) | |
when { | |
comparisonResult <= 0 -> tempSpace[resultIndex++] = input[leftIndex++] | |
else -> tempSpace[resultIndex++] = input[rightIndex++] | |
} | |
} | |
while (leftIndex < leftEnd) { | |
tempSpace[resultIndex++] = input[leftIndex++] | |
} | |
while (rightIndex < rightEnd) { | |
tempSpace[resultIndex++] = input[rightIndex++] | |
} | |
tempSpace.copyInto(input, leftStart, endIndex = resultIndex) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment