Last active
August 17, 2022 16:23
-
-
Save omarzer0/ef0b81a1109443b3b10cb7e0f76c8a54 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm using kotlin
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
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