I need to sort the doubly linked list by using quicksort algorithm. Used recursion for sorting. And my partitioning function is same as the one we used in arrays. But I faced a hard time with tracking the current head node and tail node in each list.
public void sort() {
Node la = getLast(head);
last = la;
quickSort(head, last);
}
public void quickSort(Node newhead, Node newlast) {
if(newhead == null || newlast == null) {
return;
}
if(newhead == newlast) {
return;
}
Node parti = partition(newhead,newlast);
if(parti != head)
quickSort(newhead, parti.prev);
if(parti != last)
newlast = acualTail;
quickSort(parti.next, newlast);
}
public Node partition(Node newHead, Node newLast) {
//Node actHead = newHead;
//Node acLast = newLast;
Node current = newHead;
Node p = newLast;
while(current != p) {
if(current.data > p.data) {
Node next = current.next;
current.next.prev = current.prev;
if(current.prev != null)
current.prev.next = current.next;
current.next = newLast.next;
current.prev = newLast;
newLast.next = current;
//head = next;
if(current == newHead)
newHead = next;
newLast = current;
current = next;
}
else {
current = current.next;
}
}
head= newHead;
last = newLast;
return p;
}