Quick Sort on Linked List | Practice | GeeksforGeeks

Sort the given Linked List using quicksort. which takes O(n^2) time in worst case and O(nLogn) in average and best cases, otherwise you may get TLE.
Input:
In this problem, method takes 1 argument: address of the head of the linked list. The function should not read any input from stdin/console.
The struct Node has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.
Output:
Set *headRef to head of resultant linked list.
User Task:
The task is to complete the function quickSort() which should set the *headRef to head of the resultant linked list.
Constraints:
1<=T<=100
1<=N<=200
Note: If you use "Test" or "Expected Output Button" use below example format

Example:
Input:
2
3
1 6 2
4
1 9 3 8
Output:
1 2 6
1 3 8 9
Explanation:
Testcase 1: After sorting the nodes, we have 1, 2 and 6.
Testcase 2: After sorting the nodes, we have 1, 3, 8 and 9.
 
+1
vaishantmakan1 week ago
✅✅✅  C++ Accepted Simple QuickSort Code !!!! 
void swapVal(node* first, node* sec)
{
    int temp = first->data;
    first->data = sec->data;
    sec->data = temp;
}

node* partition(node* start, node* end)
{
    int pivotVal = start->data;
    node* i = start;
    node* j = start->next;
    
    while(j != end)
    {
        if(j->data < pivotVal)
        {
            i = i->next;
            swapVal(i,j);
        }
        j = j->next;
    }
    swapVal(i, start);
    return i;
}

void QuickSort(node* start, node* end)
{
    if(start != end)
    {
        node* pivot = partition(start, end);
        QuickSort(start, pivot);
        QuickSort(pivot->next, end);   
    }
}

//you have to complete this function
void quickSort(struct node **headRef) {
    
    QuickSort(*headRef, NULL);
}
+1
prateek_jakhar1 week ago
JAVA QUICKSORT ACCEPTED
public static Node quickSort(Node head)
    {
        if(head == null) return null;
        
        Node pivot = head;
        head = head.next;
        pivot.next = null;
        if(head==null) return pivot;
        Node small = new Node(0);
        Node large = new Node(0);
        Node s = small;
        Node l = large;
        Node p = pivot;
        while(head!=null){
            if(head.data<pivot.data){
                s.next = head;
                s = s.next;
            }else if(head.data>pivot.data){
                l.next = head;
                l = l.next;
            }else{
                p.next = head;
                p = p.next;
            }
            head = head.next;
        }
        l.next = null;
        p.next = null;
        s.next = null;
        Node ss = quickSort(small.next);
        if(ss==null){
            ss=pivot;
        }else{
            Node sss = ss;
            while(sss.next!=null) sss = sss.next;
            sss.next = pivot;
        }
        p.next = quickSort(large.next);
        return ss;
    }
0
ahmadsahil261 month ago
//Java Solution
class GfG{         public static Node partition(Node node){              Node t = node.next;       Node sw = node;       Node my = node;       Node prev = sw;       while(t!=null){                      if(t.data<=my.data){               prev = sw;               sw = sw.next;               int temp = t.data;               t.data = sw.data;               sw.data = temp;                          }                      t = t.next;                  }       int temp = sw.data;       sw.data = my.data;       my.data = temp;       return prev;          }      public static Node quickSort(Node node)   {       //Your code here       if(node==null)           return null;              Node part = partition(node);              Node temp = part.next;       part.next = null;              if(node!=part)           quickSort(node);       if(node==part)           quickSort(temp);       else if(temp!=null)           quickSort(temp.next);              part.next = temp;              return node;   }      }
+1
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION (SORTING ACTUAL NODES)
class GfG{
   
   static class Triplet{
       Node left,pivot,right;
       Triplet(Node left, Node pivot, Node right){
           this.left = left;
           this.pivot = pivot;
           this.right = right;
       }
   }
   
   static Triplet getPivot(Node head){
       Node pivot = head;
       head = head.next;
       pivot.next = null;
       Node left = new Node(0);
       Node right = new Node(0);
       Node lptr = left;
       Node rptr = right;
       while(head!=null){
           if(head.data<pivot.data){
               lptr.next = head;
               lptr = lptr.next;
           }else{
               rptr.next = head;
               rptr = rptr.next;
           }
           head = head.next;
       }
       if(lptr!=null) lptr.next = null;
       if(rptr!=null) rptr.next = null;
       return new Triplet(left.next,pivot,right.next);
   }
   
   public static Node quickSort(Node node){
       //Your code here
       if(node==null || node.next==null) return node;
       Triplet curr = getPivot(node);
       curr.left = quickSort(curr.left);
       curr.right = quickSort(curr.right);
       curr.pivot.next = curr.right;
       if(curr.left==null) return curr.pivot;
       Node temp = curr.left;
       while(temp.next!=null) temp = temp.next;
       temp.next = curr.pivot;
       return curr.left;
   }
}
-1
emmanueluluabuike2 months ago
Simple Java solution
// Example case 1, 2 and 6 for explanation below
    public static Node quickSort(Node node){
        //Your code here
        ArrayList<Integer> arr = new ArrayList<>();
        Node curr = node;
        int i = 0;
        Node dummy = new Node(0);
        Node newNode = dummy;
        
        if(curr == null) return null;
        
        //Push all of the nodes into an arrayList to make sorting easier
        while(curr != null){
            arr.add(curr.data);
            curr = curr.next;
        }
        
        Collections.sort(arr); // Sorting the arrayList
        
        while(i < arr.size()){ // inserting each node.data from the arrayList into newNode
            newNode.next = new Node(arr.get(i)); // adding to new node which is 0 -> 1 -> 2 -> 6. Note 0 is already present because we added it in the begining
            newNode = newNode.next; // allows newNode to be added until it equals null
            i++;
        }
        
        return dummy.next; // We are returning dummy.next because if we just return dummy, 0 will be included which is added initially
    }
    
-2
hrithikrsgupta2 months ago
#define val data
node* quicksort(node *head,node *null){         if(head == null || head->next==null) return head;         node *slow=head,*fast=head;      while(fast->next!=null && fast->next->next!=null){              slow=slow->next;       fast=fast->next->next;          }      node *mid = slow;      node *sentinalSmall = new node(-1);   node *sentinalLarge = new node(-1);      node *small = sentinalSmall,*large = sentinalLarge,*p=head;      while(p!=null){              if(p->val < mid->val){           small->next = p;           small=small->next;                  }else if(p!=mid){           large->next = p;           large = large->next;       }       p=p->next;   }      large->next = null;      mid->next = sentinalLarge->next;   small->next = mid;     node *mHead = quicksort(sentinalSmall->next,mid);  mid->next = quicksort(mid->next,null);  return mHead;}
void quickSort(struct node **headRef) {   node *head = *headRef;      *headRef = quicksort(head,NULL);      }
+2
jeff9203052 months ago
node *partition(node *&front, node *&rear) {
    node *temp, *output = front;
    if (front == rear)
        return front;
    int pivot = front->data;
    node **curr = &(front->next);
    while (*curr != rear->next) {
        if ((*curr)->data < pivot) {
            temp = *curr;
            if (*curr == rear) {
                node *temp_rear=output;
                while(temp_rear->next!=temp)
                    temp_rear=temp_rear->next;
                rear =temp_rear;
            }
            *curr = (*curr)->next;
            push(&front, temp->data);
            free(temp);
            temp = nullptr;
            continue;
        }
        curr = &((*curr)->next);
    }

    return output;
}

void _quickSort(node *&front, node *&rear) {
    node *middle = partition(front, rear);

    if (middle != front) {
        // curr = middle->prev
        node *curr = front;
        while (curr->next != middle)
            curr = curr->next;
        _quickSort(front, curr);
    }

    if (middle != rear)
        _quickSort(middle->next, rear);
}

//you have to complete this function
void quickSort(struct node **headRef) {
    if ((*headRef)->next == nullptr)
        return;
    node *back = *headRef;
    while (back->next != nullptr)
        back = back->next;

    _quickSort(*headRef, back);
}
+2
ruchitchudasama1232 months ago
node* partition(node* head,node* tail){
   int pivot=head->data;
   node* p=head;
   node* q=head;
   while(q!=tail){
       if(q->data<pivot){
           p=p->next;
           swap(p->data,q->data);
       }
       q=q->next;
   }
   swap(p->data,head->data);// do not swap with pivot swap with originsl list
   return p;
}
void quick(node* head,node* tail){
   if(head!=tail){
       node* pivot=partition(head,tail);
       quick(head,pivot);
       quick(pivot->next,tail);
   }
}
void quickSort(struct node **headRef) {
   quick(*headRef,NULL);
}
-9
kushang30923 months ago
void quickSort(struct node **head){      struct node *t=new node(0);
   for(struct node *i=*head; i!=NULL; i=i->next)   {       for(struct node *j=i->next; j!=NULL;j=j->next)       {           if(i->data > j->data)           {               t->data=i->data;               i->data=j->data;               j->data=t->data;           }       }   }   }
+1
prajval223 months ago
//simplest approach
node *partition(node *head,node *tail){   int pivot = head->data;   node *p = head;   node *q = head;   while(q!=tail){       if(q->data<pivot){           p = p->next;           swap(p->data,q->data);       }       q = q->next;   }   swap(p->data,head->data);   return p;}
void quick(node *head,node *tail){   if(head!=tail){       node *index = partition(head,tail);       quick(head,index);       quick(index->next,tail);   }    }
void quickSort(struct node **headRef) {      quick(*headRef,NULL);   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.