-
Notifications
You must be signed in to change notification settings - Fork 108
/
MergeSort.kt
51 lines (41 loc) · 1.15 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
50
51
/**
* Created by jens on 3/8/17.
*/
fun mergeSort(list: List<Int>): List<Int> {
if (list.size <= 1) {
return list
}
val middle = list.size / 2
var left = list.subList(0,middle);
var right = list.subList(middle,list.size);
return merge(mergeSort(left), mergeSort(right))
}
fun merge(left: List<Int>, right: List<Int>): List<Int> {
var indexLeft = 0
var indexRight = 0
var newList : MutableList<Int> = mutableListOf()
while (indexLeft < left.count() && indexRight < right.count()) {
if (left[indexLeft] <= right[indexRight]) {
newList.add(left[indexLeft])
indexLeft++
} else {
newList.add(right[indexRight])
indexRight++
}
}
while (indexLeft < left.size) {
newList.add(left[indexLeft])
indexLeft++
}
while (indexRight < right.size) {
newList.add(right[indexRight])
indexRight++
}
return newList;
}
fun main(args: Array<String>) {
val numbers = mutableListOf(38,27,43,3,9,82,10)
val sortedList = mergeSort(numbers)
println("Unsorted: $numbers")
println("Sorted: $sortedList")
}