所以我正在尝试使用Insertion sort algorythm对一个linkList进行排序,我在网上找到的就是人们比较整数。我的问题是我需要按类类型排序,所以我已经实现了策略模式Strategy pattern on wikipedia通过将SortingStrategy作为我的linkedList类的成员。
这是使用比较器的inerstionSort。
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();
}
这是我想要的顺序:方形,矩形,圆形,椭圆形,直线 所以我用这种方式实现了我的比较器:
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;
}
}
我很确定问题不是来自插入排序,而是来自我的比较器......
N.B:对不起我糟糕的英文写作...... 我知道他们已经是java中的linkList类和运算符,但是我不能使用它们,因为它是我们设置中的约束。感谢您的帮助!