forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.kt
49 lines (41 loc) · 1.19 KB
/
MergeSort.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fun mergeSort(arr: IntArray): IntArray {
if (arr.size <= 1) {
return arr
}
val middle = arr.size / 2
val left = arr.copyOfRange(0, middle)
val right = arr.copyOfRange(middle, arr.size)
return merge(mergeSort(left), mergeSort(right))
}
fun merge(left: IntArray, right: IntArray): IntArray {
var result = IntArray(left.size + right.size)
var leftIndex = 0
var rightIndex = 0
var resultIndex = 0
while (leftIndex < left.size && rightIndex < right.size) {
if (left[leftIndex] < right[rightIndex]) {
result[resultIndex] = left[leftIndex]
leftIndex++
} else {
result[resultIndex] = right[rightIndex]
rightIndex++
}
resultIndex++
}
while (leftIndex < left.size) {
result[resultIndex] = left[leftIndex]
leftIndex++
resultIndex++
}
while (rightIndex < right.size) {
result[resultIndex] = right[rightIndex]
rightIndex++
resultIndex++
}
return result
}
fun main() {
val arr = intArrayOf(12, 11, 13, 5, 6, 7)
val sortedArray = mergeSort(arr)
println("Sorted array: ${sortedArray.joinToString(", ")}")
}