Skip to content

Instantly share code, notes, and snippets.

@omarzer0
Last active August 17, 2022 16:23
Show Gist options
  • Save omarzer0/ef0b81a1109443b3b10cb7e0f76c8a54 to your computer and use it in GitHub Desktop.
Save omarzer0/ef0b81a1109443b3b10cb7e0f76c8a54 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm using kotlin
fun main() {
val arr = arrayOf(9, 3, 6, 7, 3, 2, 1, 5, 4, 7, 5)
mergeSort(arr)
println(arr.contentToString())
}
fun mergeSort(inputArray: Array<Int>) {
val inputLength = inputArray.size
if (inputLength < 2) return
val midIndex = inputLength / 2 // 11 => 5 , 6
val leftHalf = Array(midIndex) { it }
val rightHalf = Array(inputLength - midIndex) { it } // 11 - 5 = 6
leftHalf.forEachIndexed { index, _ ->
leftHalf[index] = inputArray[index]
}
rightHalf.forEachIndexed { index, _ ->
rightHalf[index] = inputArray[index + midIndex]
}
mergeSort(leftHalf)
mergeSort(rightHalf)
merge(inputArray, leftHalf, rightHalf)
}
fun merge(inputArray: Array<Int>, leftHalf: Array<Int>, rightHalf: Array<Int>) {
val leftSize = leftHalf.size
val rightSize = rightHalf.size
var i = 0
var j = 0
var k = 0
while (i < leftSize && j < rightSize) {
if (leftHalf[i] < rightHalf[i]) {
inputArray[k] = leftHalf[i]
i++
} else {
inputArray[k] = rightHalf[j]
j++
}
k++
}
while (i < leftSize) {
inputArray[k] = leftHalf[i]
i++
k++
}
while (j < rightSize) {
inputArray[k] = rightHalf[j]
j++
k++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment