Recursive selection sort for singly linked list | Swapping node links

30 Mar, 2022
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data.  
Examples: 
Input : 10 -> 12 -> 8 -> 4 -> 6
Output : 4 -> 6 -> 8 -> 10 -> 12 
In Selection Sort, we first find the minimum element, swap it with the beginning node and recur for the remaining list. Below is the recursive implementation of these steps for the linked list. 
recurSelectionSort(head)
     if head->next == NULL
         return head
     Initialize min = head
     Initialize beforeMin = NULL
     Initialize ptr = head
    
     while ptr->next != NULL 
         if min->data > ptr->next->data
         min = ptr->next
         beforeMin = ptr
     ptr = ptr->next    
    
     if min != head
         swapNodes(&head, head, min, beforeMin)
    
     head->next = recurSelectionSort(head->next)
     return head

swapNodes(head_ref, currX, currY, prevY)
     head_ref = currY
     prevY->next = currX

     Initialize temp = currY->next
     currY->next = currX->next
     currX->next  = temp    
The swapNodes(head_ref, currX, currY, prevY) is based on the approach discussed here but it has been modified accordingly for the implementation of this post. 
C++
Java
Python
C#
Javascript
// C++ implementation of recursive selection sort// for singly linked list | Swapping node links#include <bits/stdc++.h>using namespace std; // A Linked list nodestruct Node {    int data;    struct Node* next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datavoid swapNodes(struct Node** head_ref, struct Node* currX,               struct Node* currY, struct Node* prevY){    // make 'currY' as new head    *head_ref = currY;     // adjust links    prevY->next = currX;     // Swap next pointers    struct Node* temp = currY->next;    currY->next = currX->next;    currX->next = temp;} // function to sort the linked list using// recursive selection sort techniquestruct Node* recurSelectionSort(struct Node* head){    // if there is only a single node    if (head->next == NULL)        return head;     // 'min' - pointer to store the node having    // minimum data value    struct Node* min = head;     // 'beforeMin' - pointer to store node previous    // to 'min' node    struct Node* beforeMin = NULL;    struct Node* ptr;     // traverse the list till the last node    for (ptr = head; ptr->next != NULL; ptr = ptr->next) {         // if true, then update 'min' and 'beforeMin'        if (ptr->next->data < min->data) {            min = ptr->next;            beforeMin = ptr;        }    }     // if 'min' and 'head' are not same,    // swap the head node with the 'min' node    if (min != head)        swapNodes(&head, head, min, beforeMin);     // recursively sort the remaining list    head->next = recurSelectionSort(head->next);     return head;} // function to sort the given linked listvoid sort(struct Node** head_ref){    // if list is empty    if ((*head_ref) == NULL)        return;     // sort the list using recursive selection    // sort technique    *head_ref = recurSelectionSort(*head_ref);} // function to insert a node at the// beginning of the linked listvoid push(struct Node** head_ref, int new_data){    // allocate node    struct Node* new_node =         (struct Node*)malloc(sizeof(struct Node));     // put in the data    new_node->data = new_data;     // link the old list to the new node    new_node->next = (*head_ref);     // move the head to point to the new node    (*head_ref) = new_node;} // function to print the linked listvoid printList(struct Node* head){    while (head != NULL) {        cout << head->data << " ";        head = head->next;    }} // Driver program to test aboveint main(){    struct Node* head = NULL;     // create linked list 10->12->8->4->6    push(&head, 6);    push(&head, 4);    push(&head, 8);    push(&head, 12);    push(&head, 10);     cout << "Linked list before sorting:n";    printList(head);     // sort the linked list    sort(&head);     cout << "\nLinked list after sorting:n";    printList(head);     return 0;}
// Java implementation of recursive selection sort// for singly linked list | Swapping node linksclass GFG{     // A Linked list nodestatic class Node{    int data;    Node next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datastatic Node swapNodes( Node head_ref, Node currX,                        Node currY, Node prevY){    // make 'currY' as new head    head_ref = currY;     // adjust links    prevY.next = currX;     // Swap next pointers    Node temp = currY.next;    currY.next = currX.next;    currX.next = temp;    return head_ref;} // function to sort the linked list using// recursive selection sort techniquestatic Node recurSelectionSort( Node head){    // if there is only a single node    if (head.next == null)        return head;     // 'min' - pointer to store the node having    // minimum data value    Node min = head;     // 'beforeMin' - pointer to store node previous    // to 'min' node    Node beforeMin = null;    Node ptr;     // traverse the list till the last node    for (ptr = head; ptr.next != null; ptr = ptr.next)    {         // if true, then update 'min' and 'beforeMin'        if (ptr.next.data < min.data)        {            min = ptr.next;            beforeMin = ptr;        }    }     // if 'min' and 'head' are not same,    // swap the head node with the 'min' node    if (min != head)        head = swapNodes(head, head, min, beforeMin);     // recursively sort the remaining list    head.next = recurSelectionSort(head.next);     return head;} // function to sort the given linked liststatic Node sort( Node head_ref){    // if list is empty    if ((head_ref) == null)        return null;     // sort the list using recursive selection    // sort technique    head_ref = recurSelectionSort(head_ref);    return head_ref;} // function to insert a node at the// beginning of the linked liststatic Node push( Node head_ref, int new_data){    // allocate node    Node new_node = new Node();     // put in the data    new_node.data = new_data;     // link the old list to the new node    new_node.next = (head_ref);     // move the head to point to the new node    (head_ref) = new_node;    return head_ref;} // function to print the linked liststatic void printList( Node head){    while (head != null)    {        System.out.print( head.data + " ");        head = head.next;    }} // Driver codepublic static void main(String args[]){    Node head = null;     // create linked list 10.12.8.4.6    head = push(head, 6);    head = push(head, 4);    head = push(head, 8);    head = push(head, 12);    head = push(head, 10);     System.out.println( "Linked list before sorting:");    printList(head);     // sort the linked list    head = sort(head);     System.out.print( "\nLinked list after sorting:");    printList(head);}} // This code is contributed by Arnab Kundu
# Python implementation of recursive selection sort# for singly linked list | Swapping node links # Linked List nodeclass Node:    def __init__(self, data):        self.data = data        self.next = None # function to swap nodes 'currX' and 'currY' in a# linked list without swapping datadef swapNodes(head_ref, currX, currY, prevY) :     # make 'currY' as new head    head_ref = currY     # adjust links    prevY.next = currX     # Swap next pointers    temp = currY.next    currY.next = currX.next    currX.next = temp    return head_ref # function to sort the linked list using# recursive selection sort techniquedef recurSelectionSort( head) :     # if there is only a single node    if (head.next == None) :        return head     # 'min' - pointer to store the node having    # minimum data value    min = head     # 'beforeMin' - pointer to store node previous    # to 'min' node    beforeMin = None    ptr = head         # traverse the list till the last node    while ( ptr.next != None ) :             # if true, then update 'min' and 'beforeMin'        if (ptr.next.data < min.data) :                     min = ptr.next            beforeMin = ptr                     ptr = ptr.next         # if 'min' and 'head' are not same,    # swap the head node with the 'min' node    if (min != head) :        head = swapNodes(head, head, min, beforeMin)     # recursively sort the remaining list    head.next = recurSelectionSort(head.next)     return head # function to sort the given linked listdef sort( head_ref) :     # if list is empty    if ((head_ref) == None) :        return None     # sort the list using recursive selection    # sort technique    head_ref = recurSelectionSort(head_ref)    return head_ref # function to insert a node at the# beginning of the linked listdef push( head_ref, new_data) :     # allocate node    new_node = Node(0)     # put in the data    new_node.data = new_data     # link the old list to the new node    new_node.next = (head_ref)     # move the head to point to the new node    (head_ref) = new_node    return head_ref # function to print the linked listdef printList( head) :     while (head != None) :             print( head.data ,end = " ")        head = head.next     # Driver codehead = None # create linked list 10.12.8.4.6head = push(head, 6)head = push(head, 4)head = push(head, 8)head = push(head, 12)head = push(head, 10) print( "Linked list before sorting:")printList(head) # sort the linked listhead = sort(head) print( "\nLinked list after sorting:")printList(head) # This code is contributed by Arnab Kundu
// C# implementation of recursive selection sort// for singly linked list | Swapping node linksusing System;public class GFG{     // A Linked list nodepublic class Node{    public int data;    public Node next;}; // function to swap nodes 'currX' and 'currY' in a// linked list without swapping datastatic Node swapNodes(Node head_ref, Node currX,                      Node currY, Node prevY){    // make 'currY' as new head    head_ref = currY;     // adjust links    prevY.next = currX;     // Swap next pointers    Node temp = currY.next;    currY.next = currX.next;    currX.next = temp;    return head_ref;} // function to sort the linked list using// recursive selection sort techniquestatic Node recurSelectionSort(Node head){    // if there is only a single node    if (head.next == null)        return head;     // 'min' - pointer to store the node having    // minimum data value    Node min = head;     // 'beforeMin' - pointer to store node    // previous to 'min' node    Node beforeMin = null;    Node ptr;     // traverse the list till the last node    for (ptr = head; ptr.next != null;                     ptr = ptr.next)    {         // if true, then update 'min' and 'beforeMin'        if (ptr.next.data < min.data)        {            min = ptr.next;            beforeMin = ptr;        }    }     // if 'min' and 'head' are not same,    // swap the head node with the 'min' node    if (min != head)        head = swapNodes(head, head, min, beforeMin);     // recursively sort the remaining list    head.next = recurSelectionSort(head.next);     return head;} // function to sort the given linked liststatic Node sort( Node head_ref){    // if list is empty    if ((head_ref) == null)        return null;     // sort the list using recursive selection    // sort technique    head_ref = recurSelectionSort(head_ref);    return head_ref;} // function to insert a node at the// beginning of the linked liststatic Node push(Node head_ref, int new_data){    // allocate node    Node new_node = new Node();     // put in the data    new_node.data = new_data;     // link the old list to the new node    new_node.next = (head_ref);     // move the head to point to the new node    (head_ref) = new_node;    return head_ref;} // function to print the linked liststatic void printList( Node head){    while (head != null)    {        Console.Write(head.data + " ");        head = head.next;    }} // Driver codepublic static void Main(String []args){    Node head = null;     // create linked list 10->12->8->4->6    head = push(head, 6);    head = push(head, 4);    head = push(head, 8);    head = push(head, 12);    head = push(head, 10);     Console.WriteLine("Linked list before sorting:");    printList(head);     // sort the linked list    head = sort(head);     Console.Write("\nLinked list after sorting:");    printList(head);}}  // This code is contributed by Princi Singh
<script>// javascript implementation of recursive selection sort// for singly linked list | Swapping node links     // A Linked list node     class Node {        constructor(val) {            this.data = val;            this.next = null;        }    }     // function to swap nodes 'currX' and 'currY' in a    // linked list without swapping data    function swapNodes(head_ref,  currX,  currY,  prevY) {        // make 'currY' as new head        head_ref = currY;         // adjust links        prevY.next = currX;         // Swap next pointers        var temp = currY.next;        currY.next = currX.next;        currX.next = temp;        return head_ref;    }     // function to sort the linked list using    // recursive selection sort technique    function recurSelectionSort(head) {        // if there is only a single node        if (head.next == null)            return head;         // 'min' - pointer to store the node having        // minimum data value        var min = head;         // 'beforeMin' - pointer to store node previous        // to 'min' node        var beforeMin = null;        var ptr;         // traverse the list till the last node        for (ptr = head; ptr.next != null; ptr = ptr.next) {             // if true, then update 'min' and 'beforeMin'            if (ptr.next.data < min.data) {                min = ptr.next;                beforeMin = ptr;            }        }         // if 'min' and 'head' are not same,        // swap the head node with the 'min' node        if (min != head)            head = swapNodes(head, head, min, beforeMin);         // recursively sort the remaining list        head.next = recurSelectionSort(head.next);         return head;    }     // function to sort the given linked list    function sort(head_ref) {        // if list is empty        if ((head_ref) == null)            return null;         // sort the list using recursive selection        // sort technique        head_ref = recurSelectionSort(head_ref);        return head_ref;    }     // function to insert a node at the    // beginning of the linked list    function push(head_ref , new_data) {        // allocate node        var new_node = new Node();         // put in the data        new_node.data = new_data;         // link the old list to the new node        new_node.next = (head_ref);         // move the head to point to the new node        (head_ref) = new_node;        return head_ref;    }     // function to print the linked list    function printList(head) {        while (head != null) {            document.write(head.data + " ");            head = head.next;        }    }     // Driver code             var head = null;         // create linked list 10.12.8.4.6        head = push(head, 6);        head = push(head, 4);        head = push(head, 8);        head = push(head, 12);        head = push(head, 10);         document.write("Linked list before sorting:<br/>");        printList(head);         // sort the linked list        head = sort(head);         document.write("<br/>Linked list after sorting:<br/>");        printList(head); // This code is contributed by todaysgaurav</script>
Output: 
Linked list before sorting:
10 12 8 4 6
Linked list after sorting:
4 6 8 10 12
Time Complexity: O(n2)
Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
andrew1234
princi singh
todaysgaurav
khushboogoyal499
rohan07
Linked-List-Sorting
Linked List
Sorting
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.