我正在为双重链接列表实现快速排序。
我已尝试过这篇文章的解决方案: QuickSort on Doubly Linked List
代码有效,但如果我有类似的东西:
129 149 169 3 7000 20 5000
它返回: 20 129 149 169 5000 7000
它是排序的,但第一个值在哪里?
我正在使用此代码:
public DoublyLinkedList quicksort(DoublyLinkedList in, int numOfElements) {
in.first = partition(in.first, in.first.prev);
return in;
}
private ListElement partition(ListElement first, ListElement pivotElement) {
ListElement left = first;
ListElement right = pivotElement;
while (left != pivotElement) {
if (left.getKey() > pivotElement.getKey()) {
ListElement next = left.next;
if (left == first)
first = next;
//Remove currentLeft
left.prev.next = left.next;
left.next.prev = left.prev;
//Connect with element after currentRight
left.next = right.next;
right.next.prev = left;
//Connect with pivotElement
left.prev = right;
right.next = left;
right = left; //Switch right with left, since we just swapped their positions
left = next; //Assign left to the next object (from the left part)
} else {
left = left.next;
}
}
if (first != pivotElement.prev && first != pivotElement)
first = partition(first, pivotElement.prev);
if (pivotElement != right)
partition(pivotElement.next, right);
return first;
}