sorting - Kotlin:排序 |交换操作的位置

标签 sorting kotlin quicksort software-design

我正在 Kotlin 中实现快速排序算法。为此,我创建了一个接口(interface) ISort,它带有一个类型参数和一个函数 sort。对于排序,我需要交换操作。我想知道这个交换功能的最佳位置是什么。我的想法:

1) 不幸的是,在 Kotlin 中不能保护接口(interface)函数。因此,每个类都可以在其实现中看到交换,这不太好(尽管它也不太糟糕,我同意)。

2) 把它放在 QuickSort 实现中更糟糕,因为可能有几个 ISort 接口(interface)的实现需要交换函数。

3) 我的下一个想法是创建一个单例对象,但 Kotlin 允许具有类型参数的对象。

这是接口(interface)定义:

interface ISort<T> {
  fun sort(toSort: MutableList<T>): MutableList<T>
  // 1) Putting swap here has a too high visibility
}

这是 QuickSort 类的框架:
class QuickSort<T> : ISort<T> {
  override fun sort(toSort: MutableList<T>): MutableList<T> {
    doQuickSort(toSort) // Internally uses swap
    return toSort
  }
  // 2) Putting swap here might lead to code duplication of swap
}

因此,从软件工程的角度来看,交换操作的最佳位置/位置是什么。

最佳答案

顶级功能

在文件中 sort.kt或者,

package abc.def.sort


fun <T> quicksort(list: MutableList<T>): MutableList<T> {
    ...
}

// invisible in other files, but visibie in "sort.kt"
private fun <T> swap(...) {
    ...
}

使用 swap其他排序函数,您将需要在同一文件中定义其他排序函数。 (或多次复制 swap 函数。)

推荐用于非常简单的功能。

对象作为命名空间

这类似于上面的方法,但比前一种方法更 OOP-ish。
object QuickSort {
    fun <T> sort(list: MutableList<T>): MutableList<T> {
        ...
    }

    private fun <T> swap(...) {
        ...
    }
}

或者
object Sorts {
    fun <T> quicksort(list: MutableList<T>): MutableList<T> {
        ...
    }

    // add other sort methods...

    private fun <T> swap(...) {
        ...
    }
}

但是,在 Kotlin (Best practices for top-level declarations) 中不建议这样做。

抽象类和对象的组合
swap可以通过这种方式将函数重用于其他类型。
abstract class Sort {
    abstract fun <T> sort(list: MutableList<T>): MutableList<T>

    protected fun <T> swap(...) {
        ...
    }
}

object QuickSort : Sort() {
    override fun <T> sort(list: MutableList<T>): MutableList<T> {
        ...
    }
}

我认为[制作类型参数T是类类型参数,而不是函数类型参数] 会使问题变得不必要地复杂,因为每次使用不同类型时都必须创建一个类实例 T .

关于sorting - Kotlin:排序 |交换操作的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455970/

相关文章:

android - 如何在 Kotlin 中将 setter 设为私有(private),用于非最终变量?

c++ - 快速排序显然是选择o(n^2)当左或最右元素作为枢轴时

c - C 中的快速排序未按预期工作

javascript - 使用没有 sort() 方法的数字对数组进行排序

android - 使用 Kotlin 在 fragment 中创建 AlertDialog

android - 写入权限不起作用 - 范围存储 Android SDK 30(又名 Android 11)

python - 随机快速排序中的最大递归深度误差

c++ - 排序算法的切换输入

C# - 对结构内的列表进行排序

javascript - 对字符串中的元素进行排序