Skip to content

Commit db1bee1

Browse files
author
taufiqhidayah
committed
add Kotlin Merge Sort
1 parent d1ee573 commit db1bee1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Kotlin/MergeSort.kt

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Created by jens on 3/8/17.
3+
*/
4+
5+
fun mergeSort(list: List<Int>): List<Int> {
6+
if (list.size <= 1) {
7+
return list
8+
}
9+
10+
val middle = list.size / 2
11+
var left = list.subList(0,middle);
12+
var right = list.subList(middle,list.size);
13+
14+
return merge(mergeSort(left), mergeSort(right))
15+
}
16+
17+
18+
fun merge(left: List<Int>, right: List<Int>): List<Int> {
19+
var indexLeft = 0
20+
var indexRight = 0
21+
var newList : MutableList<Int> = mutableListOf()
22+
23+
while (indexLeft < left.count() && indexRight < right.count()) {
24+
if (left[indexLeft] <= right[indexRight]) {
25+
newList.add(left[indexLeft])
26+
indexLeft++
27+
} else {
28+
newList.add(right[indexRight])
29+
indexRight++
30+
}
31+
}
32+
33+
while (indexLeft < left.size) {
34+
newList.add(left[indexLeft])
35+
indexLeft++
36+
}
37+
38+
while (indexRight < right.size) {
39+
newList.add(right[indexRight])
40+
indexRight++
41+
}
42+
43+
return newList;
44+
}
45+
46+
fun main(args: Array<String>) {
47+
val numbers = mutableListOf(38,27,43,3,9,82,10)
48+
val sortedList = mergeSort(numbers)
49+
println("Unsorted: $numbers")
50+
println("Sorted: $sortedList")
51+
}

0 commit comments

Comments
 (0)