Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this Kotlin DSA implementation can be compared directly with the other languages.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.
Visual walkthrough
Basic Implementation
basic.kt
fun mergeSort(values: List<Int>): List<Int> {
if (values.size <= 1) return values
val mid = values.size / 2
val left = mergeSort(values.subList(0, mid))
val right = mergeSort(values.subList(mid, values.size))
val merged = mutableListOf<Int>()
var i = 0
var j = 0
while (i < left.size && j < right.size) {
if (left[i] <= right[j]) merged.add(left[i++]) else merged.add(right[j++])
}
merged.addAll(left.drop(i))
merged.addAll(right.drop(j))
return merged
}
fun main() {
val arr = listOf(5, 1, 4, 2, 8)
println(mergeSort(arr).joinToString(prefix = "[", postfix = "]"))
}
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- Kotlin stores the input in
val arr = listOf(5, 1, 4, 2, 8), avalbinding to a read-onlyList<Int>; the source never mutatesarr. - The recursive signature is
mergeSort(values: List<Int>): List<Int>.if (values.size <= 1) return valuesis the base case, while non-base calls build and return a newmergedlist. - Splitting uses
values.subList(0, mid)andvalues.subList(mid, values.size); those list views are passed into recursive calls before merging. - The merge buffer is
val merged = mutableListOf<Int>(). Cursor indexesiandjare mutablevar Intvalues that advance withleft[i++]andright[j++]. if (left[i] <= right[j])usesIntcomparison and takes the left value on ties, preserving stable ordering for equal values.- Remaining elements are appended with
merged.addAll(left.drop(i))andmerged.addAll(right.drop(j));dropcreates suffix lists for the leftovers. - The trace shows
[5, 1, 4, 2, 8]split into[5, 1]and[4, 2, 8], sorted to[1, 5]and[2, 4, 8], then merged into[1, 2, 4, 5, 8]. println(mergeSort(arr).joinToString(prefix = "[", postfix = "]"))formats the returned list as[1, 2, 4, 5, 8].