[英]How do I get insertion sort to work with a doubly linked list
I cannot get this method to sort the Doubly Linked List from least to greatest. 我无法使用此方法将双向链接列表从最小到最大排序。
My input is : MyLinkedList: 3.0, 4.0, 2.0, 69.0, 76.0, 22.0, 341.0, 15.0 我的输入是:MyLinkedList:3.0、4.0、2.0、69.0、76.0、22.0、341.0、15.0
public void insertionSort(Comparator<? super E> compare) {
DLinkedNode<E> tempI = head.next;
for (int i = 1; i < size && tempI.next != null; i++) {
E temp = tempI.data;
int j;
DLinkedNode<E> tempJ = tempI.prev;
for (j = i-1; j >= 0 && tempJ.prev != null; j--) {
if (compare.compare(tempJ.data, temp) <= 0){
printLinkedList();
System.out.println("");
tempJ.next.data = tempJ.data;
}
tempJ = tempJ.prev;//j--;
}//end for
tempJ.next.data = temp;
tempI = tempI.next;//i++;
}//end for
}// end insertionSort
The output after each iteration of the inner for loop is: 内部for循环的每次迭代之后的输出为:
MyLinkedList: 3.0, 2.0, 2.0, 69.0, 76.0, 22.0, 341.0, 15.0
MyLinkedList: 3.0, 2.0, 2.0, 2.0, 76.0, 22.0, 341.0, 15.0
MyLinkedList: 3.0, 69.0, 2.0, 2.0, 76.0, 22.0, 341.0, 15.0
MyLinkedList: 3.0, 69.0, 2.0, 2.0, 2.0, 22.0, 341.0, 15.0
MyLinkedList: 3.0, 69.0, 2.0, 2.0, 2.0, 22.0, 341.0, 15.0
MyLinkedList: 3.0, 76.0, 69.0, 2.0, 2.0, 22.0, 341.0, 15.0
MyLinkedList: 3.0, 76.0, 69.0, 2.0, 2.0, 2.0, 341.0, 15.0
MyLinkedList: 3.0, 22.0, 69.0, 2.0, 2.0, 2.0, 341.0, 15.0
MyLinkedList: 3.0, 22.0, 69.0, 2.0, 2.0, 2.0, 2.0, 15.0
MyLinkedList: 3.0, 22.0, 69.0, 2.0, 2.0, 2.0, 2.0, 15.0
MyLinkedList: 3.0, 22.0, 69.0, 2.0, 2.0, 2.0, 2.0, 15.0
MyLinkedList: 3.0, 22.0, 69.0, 69.0, 2.0, 2.0, 2.0, 15.0
MyLinkedList: 3.0, 341.0, 22.0, 69.0, 2.0, 2.0, 2.0, 15.0
comparable method is: 可比较的方法是:
public class DoubleComp implements Comparator<Double> {
public int compare(Double a1, Double a2) {
double foo = ((double) a1 - (double) a2);
return (int) foo;
}
}
Use comparable instead of comparator try with since you are comparing only double value. 因为您只比较双精度值,所以请使用可比而不是比较器尝试。
public class DoubleComp implements Comparable<Double> {
public int compareTo(Double a1, Double a2) {
double foo = ((double) a1 - (double) a2);
return (int) foo;
}
}
Double.compare(double d1, double d2)
to compare doubles if you are using JDK 7 or later. Double.compare(double d1, double d2)
使用Double.compare(double d1, double d2)
比较双精度数。 Sorting looks really messed up. 排序看起来真的很混乱。 Try using the following approach:
尝试使用以下方法:
Node root; Comparator comp; Node current = root; while (current.next != null) { E data = current.data; Node i = current; while (i.previous != null && comp.compare(data, i.previous.data) < 0) { i.data = i.previous.data; i = previous; } i.data = data; current = current.next; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.