2018-01-05 | learn

kotlin 模仿 scala 写个 qsort

Cooooooooooooooooooooooooooool!

1
2
3
4
def qsort(list: List[Int]): List[Int] = list match {
case Nil => Nil
case head :: tail => qsort(tail.filter(_ < head)) ::: head :: qsort(tail.filter(_ >= head))
}

in kotlin

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
package _play

import java.util.*

/**
* Created by Kang on 2018/1/5.
*/
fun main(args: Array<String>) {
print(qsort(arrayListOf(23, 56, 1, 63, 2, 2, 5, 3)))
}

fun qsort(list: List<Int>): List<Int> = when (list.size) {
0, 1 -> list
else -> split(list).let { (head, tail) ->
merge(merge(qsort(tail.filter { it < head }), head), qsort(tail.filter { it >= head }))
}
}

fun split(list: List<Int>) = Tuple(list[0], list.subList(1, list.size))

fun merge(head: List<Int>, tail: Int): List<Int> = ArrayList(head).apply { add(tail) }

fun merge(head: List<Int>, tail: List<Int>): List<Int> = ArrayList(head).apply { addAll(tail) }

data class Tuple(val head: Int, val tail: List<Int>)

output

1
2
[1, 2, 2, 3, 5, 23, 56, 63]
Process finished with exit code 0