// here the sorting happens exclusive of the end node // returns the head node after sorting the linked list struct node *quickSortRecur(struct node *head, struct node *end) { // base condition if (!head || head == end) return head; node *newHead = NULL, *newEnd = NULL; // Partition the list, newHead and newEnd will be updated // by the partition function struct node *pivot = partition(head, end, &newHead, &newEnd); // If pivot is the smallest element - no need to recur for // the left part. if (newHead != pivot) { // Set the node before the pivot node as NULL struct node *tmp = newHead; while (tmp->next != pivot) tmp = tmp->next; tmp->next = NULL; // Recur for the list before pivot newHead = quickSortRecur(newHead, tmp); // Change next of last node of the left half to pivot tmp = getTail(newHead); tmp->next = pivot; } // Recur for the list after the pivot element pivot->next = quickSortRecur(pivot->next, newEnd); return newHead; }
struct node *quickSortRecur(struct node *head, struct node *end) { if(!head || head == end) { return head; } node *newHead = NULL, *newEnd = NULL; struct node *pivot = partition(head, end, &newHead, &newEnd); if(newHead != pivot) { struct node *tmp = newHead; while(tmp->next != pivot) { tmp = tmp->next; } tmp->next = NULL; newHead = quickSortRecur(newHead, tmp); } pivot->next = quickSortRecur(pivot->next, newEnd); return newHead; }
// The main function for quick sort. This is a wrapper over recursive // function quickSortRecur() void quickSort(struct node **headRef) { (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); return; }