I'm implementing a Quick Sort for a Doubly LinkedList.
I've tried the solution of this post : QuickSort on Doubly Linked List
The code works, but if I have something like:
129 149 169 3 7000 20 5000
It returns: 20 129 149 169 5000 7000
It's sorted, but where's the first value?
I am using this code:
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;
}