用于在linkedList中插入排序的Comparator java
所以我尝试使用插入排序算法对linkedList进行排序,我在网上找到的只是比较整数的人。我的问题是我需要按类类型进行排序,因此我通过将SortingStrategy作为linkedList类的成员来实现策略模式 这是使用比较器的惯性排序用于在linkedList中插入排序的Comparator java,java,sorting,linked-list,comparator,Java,Sorting,Linked List,Comparator,所以我尝试使用插入排序算法对linkedList进行排序,我在网上找到的只是比较整数的人。我的问题是我需要按类类型进行排序,因此我通过将SortingStrategy作为linkedList类的成员来实现策略模式 这是使用比较器的惯性排序 private NodeShape InsertionSort(NodeShape head){ if (head == null || head.getNext() == null){ return head; }
private NodeShape InsertionSort(NodeShape head){
if (head == null || head.getNext() == null){
return head;
}
//create new fake node
NodeShape preHead = new NodeShape (null);
preHead.setNextNode(head);
NodeShape run = head;
//first loop
while (run != null && run.getNext() != null){
//we find the node who are not in the correct order
if (!this.getSortingStrategy().Compare(run.getShape(), run.getNext().getShape())){//run.val>run.next.val){
NodeShape innerRun = run.getNext();
NodeShape pre = preHead;
// we loop again until we find node that are not in the correct order
while ( this.getSortingStrategy().Compare(pre.getNext().getShape(),innerRun.getShape())){//pre.next.val<smallNode.val){
pre = pre.getNext();
}
//we swap the next node of the last node we found that has the correct order
NodeShape temp = pre.getNext();
pre.setNextNode(innerRun);
run.setNextNode(innerRun.getNext());
innerRun.setNextNode(temp);
}
else{
run = run.getNext();
}
}
return preHead.getNext();
}
}
我很确定问题不是来自插入排序,而是来自我的比较器
对不起,我糟糕的英语写作。。。
我知道它们已经是java中的linkedList类和运算符,但我不能使用它们,因为它是赋值中的一个约束
谢谢你的帮助 如果您不确定比较方法是否正确,请为其编写一个单元测试。只有25种可能的输入。乍一看,这个方法看起来不错(除了名称不明确,返回的是装箱的
Boolean
而不是Boolean
)是的,你说得对!5比较国的可能性。。我不知道我怎么能让它与众不同。。。我来做JUnit。。我觉得我不太喜欢说唱音乐你说的“与众不同”是什么意思?Compare
方法?可以将其称为isLeftLessThanRight
,并返回一个基元布尔值。或者您可以向Shape
界面添加一个方法isLessThan(Shape-other)
。虽然这不能解决您的问题,但可能会提高可读性。尽管如此:为每个输入编写一个单元测试,您将确定该方法是否按预期工作。我的意思是,在我正在进行的检查中,使其不同,ifs和else ifs。。但是,是的,谢谢,我将返回布尔值而不是布尔值。好吧……您可以使用动态分派,在Shape
的界面中实现lessThan(Shape other)
方法,而不是instanceof
检查,这样您就可以从instanceof
检查中解脱一半。您可以通过实现一个访问者模式来消除所有这些问题,但这对于这个目的来说是过分的。除此之外,还有一种非常丑陋但简单的方法:将形状
转换为整数(通过添加一个字段,例如,1代表正方形
,2代表矩形
)。然后,您可以简单地比较int
值,但您无法轻松添加新的形状
类。
public class SortByShapeType implements ISortStrategy {
@Override
public Boolean Compare(Shape s1, Shape s2) {
if (s1 instanceof Square) {
return true;
}else if (s1 instanceof Rectangle && !(s2 instanceof Square)) {
return true;
}else if(s1 instanceof Circle && !((s2 instanceof Square) || (s2 instanceof Rectangle))){
return true;
}else if(s1 instanceof Ellipse && !((s2 instanceof Square) || (s2 instanceof Rectangle) || (s2 instanceof Circle))){
return true;
}
return false;
}