0

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;
}
Community
  • 1
  • 1
  • So right.middle.up.left.down.throw-it-in-reverse isn't working out well :-) If it were me and I didn't feel like torturing myself, depending on the size of data, frequency of use, I would be tempted to read it into an array, sort the array and then if necessary turn it back into a doubly linked list. Would depend on a various factors. – clearlight Feb 05 '17 at 05:05
  • what's this `in.first.prev` meant to be on the first call? Is the list circular? – Henry Feb 05 '17 at 07:19
  • Yes. It's circular. – ComplexityAlg Feb 05 '17 at 14:16

0 Answers0