algorithm - 通用排序函数接受 T,但要确保 T 是可比较的

标签 algorithm sorting generics dart

我正在 Dart 中对一个简单的 MergeSort 进行泛化。

只是作为占位符,我想了一个 Node 的列表将为 List<T> 制作一个足够的包装器。由于 T 是一个对象,它本身没有compareTo、<、>、<= 等,因为它不是数字或字符串。

如何删除这些警告。

class Node<T> extends Comparable {
  T _value;
  Node(T value){
    _value = value;
  }
  //.....

}

class MergeSort<T>{
  list<Node<T>> _list;

  MergeSort(List<Node<T>> list){
    _list = list;

  }

  List<Node<T>> Sort( List<Node<T>> list ){
    _list = list;
    //.....
  }
}

我遇到的问题是,在合并排序中,我需要比较节点,这已经足够了。我实现operator ==等来处理这些情况,或 operator <对于那些情况。自从我扩展了 Comparable 以来,我也有 compareTo由于字符串。

我不确定如何适应传递给 Node、T 的类,并且我不知道是否有办法拥有它 expect数字、字符串等

完整的类实现+可共享的dartpad:https://dartpad.dartlang.org/645157fb547da482fc2b

class Node<T> extends Comparable{
  T _value;
  Node(T item){
    _value = item;
  }

  T getValue () => _value;

  bool operator ==(other) => identical(this, other);
  bool operator <( other){
    if (other is! T){
      return false;
    }

    //other is of same type, T.
    if (_value < (other as Node<T>).getValue()){
      return true;
    }
    return false;
  }
  bool operator <= (other){
    return (this == other) || (this < other);
  }

  int compareTo (other){
    if (this == other){ 
      return 0;  
    }
    if (this < other) { 
      return -1; 
    }
    return 1;  
  }
}

也许拥有一个节点包装器太多了?我觉得我也许可以去掉 Node 类,只拥有一个 T 列表,但是当涉及到列表元素的比较时,问题就会被推到 MergeSort 中。

最佳答案

我想你正在寻找的是

class Node<T extends Comparable>

class MergeSort<T extends Comparable>{

但是Comparable没有实现>/< 。如果您想使用这些,您可以创建自己的父类(super class),并且需要实现该类。

关于algorithm - 通用排序函数接受 T,但要确保 T 是可比较的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122891/

相关文章:

swift - 我可以在 Swift 中将默认类型分配给泛型类型 T 吗?

Java泛型列表中,如何处理List<MyClass<?>>

c - 如何合并两个字符串

.net - Microsoft GraphEngine LIKQ 查询

javascript - 递归展平一组数组的算法

javascript - 如何在js中用符号对列表进行排序

algorithm - 固定大小数组/列表的在线排序算法

algorithm - 基数排序 : LSD versus MSD versions

java - 给定一批 0-9 的整数,在我用完某个整数之前我能写的最后一个数字是多少?

java泛型方法签名