refactor Sorter & Mergesort

This commit is contained in:
Raffaele Mignone 2019-04-06 23:25:15 +02:00
parent aeb32837a9
commit 4f29c6bfbf
Signed by: norangebit
GPG Key ID: F5255658CB220573
2 changed files with 16 additions and 18 deletions

View File

@ -25,20 +25,8 @@
package it.norangeb.algorithms.sorting
object Mergesort : Sorter {
override fun <T : Comparable<T>> sort(array: Array<T>) {
sort(array) { t1, t2 -> t1 < t2 }
}
override fun <T, C : Comparable<C>> sortBy(array: Array<T>, compareBy: (T) -> C) {
sort(array) { t1, t2 -> compareBy(t1) < compareBy(t2) }
}
override fun <T> sortWith(array: Array<T>, compare: (T, T) -> Int) {
sort(array) { t1, t2 -> compare(t1, t2) < 0 }
}
private fun <T> sort(array: Array<T>, isLess: (T, T) -> Boolean) {
object Mergesort : Sorter() {
override fun <T> sort(array: Array<T>, isLess: (T, T) -> Boolean) {
val auxiliary = arrayOfNulls<Any>(array.size) as Array<T>
sort(array, auxiliary, 0, array.size - 1, isLess)
}

View File

@ -25,8 +25,18 @@
package it.norangeb.algorithms.sorting
interface Sorter {
fun <T : Comparable<T>> sort(array: Array<T>)
fun <T, C : Comparable<C>> sortBy(array: Array<T>, compareBy: (T) -> C)
fun <T> sortWith(array: Array<T>, compare: (T, T) -> Int)
abstract class Sorter {
fun <T : Comparable<T>> sort(array: Array<T>) {
sort(array) { t1, t2 -> t1 < t2 }
}
fun <T, C : Comparable<C>> sortBy(array: Array<T>, compareBy: (T) -> C) {
sort(array) { t1, t2 -> compareBy(t1) < compareBy(t2) }
}
fun <T> sortWith(array: Array<T>, compare: (T, T) -> Int) {
sort(array) { t1, t2 -> compare(t1, t2) < 0 }
}
abstract fun <T> sort(array: Array<T>, isLess: (T, T) -> Boolean)
}