From 4f29c6bfbf08fbce8f7a7b82555e2c6ab5f06da3 Mon Sep 17 00:00:00 2001 From: norangebit Date: Sat, 6 Apr 2019 23:25:15 +0200 Subject: [PATCH] refactor Sorter & Mergesort --- .../norangeb/algorithms/sorting/Mergesort.kt | 16 ++-------------- .../it/norangeb/algorithms/sorting/Sorter.kt | 18 ++++++++++++++---- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/src/main/kotlin/it/norangeb/algorithms/sorting/Mergesort.kt b/src/main/kotlin/it/norangeb/algorithms/sorting/Mergesort.kt index d0cfcdd..589cab1 100644 --- a/src/main/kotlin/it/norangeb/algorithms/sorting/Mergesort.kt +++ b/src/main/kotlin/it/norangeb/algorithms/sorting/Mergesort.kt @@ -25,20 +25,8 @@ package it.norangeb.algorithms.sorting -object Mergesort : Sorter { - override fun > sort(array: Array) { - sort(array) { t1, t2 -> t1 < t2 } - } - - override fun > sortBy(array: Array, compareBy: (T) -> C) { - sort(array) { t1, t2 -> compareBy(t1) < compareBy(t2) } - } - - override fun sortWith(array: Array, compare: (T, T) -> Int) { - sort(array) { t1, t2 -> compare(t1, t2) < 0 } - } - - private fun sort(array: Array, isLess: (T, T) -> Boolean) { +object Mergesort : Sorter() { + override fun sort(array: Array, isLess: (T, T) -> Boolean) { val auxiliary = arrayOfNulls(array.size) as Array sort(array, auxiliary, 0, array.size - 1, isLess) } diff --git a/src/main/kotlin/it/norangeb/algorithms/sorting/Sorter.kt b/src/main/kotlin/it/norangeb/algorithms/sorting/Sorter.kt index 19d9dee..75fbf6e 100644 --- a/src/main/kotlin/it/norangeb/algorithms/sorting/Sorter.kt +++ b/src/main/kotlin/it/norangeb/algorithms/sorting/Sorter.kt @@ -25,8 +25,18 @@ package it.norangeb.algorithms.sorting -interface Sorter { - fun > sort(array: Array) - fun > sortBy(array: Array, compareBy: (T) -> C) - fun sortWith(array: Array, compare: (T, T) -> Int) +abstract class Sorter { + fun > sort(array: Array) { + sort(array) { t1, t2 -> t1 < t2 } + } + + fun > sortBy(array: Array, compareBy: (T) -> C) { + sort(array) { t1, t2 -> compareBy(t1) < compareBy(t2) } + } + + fun sortWith(array: Array, compare: (T, T) -> Int) { + sort(array) { t1, t2 -> compare(t1, t2) < 0 } + } + + abstract fun sort(array: Array, isLess: (T, T) -> Boolean) } \ No newline at end of file