Given a singly linked list containing n nodes. The problem is to sort the list using recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping nodes data.
Input : 10 -> 12 -> 8 -> 4 -> 6 Output : 4 -> 6 -> 8 -> 10 -> 12
In Selection Sort, we first find minimum element, swap it with the beginning node and recur for remaining list. Below is recursive implementation of these steps for 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 is modified accordingly for the implementation of this post.
Linked list before sorting: 10 12 8 4 6 Linked list after sorting: 4 6 8 10 12
Time Complexity: O(n2)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
- Sort a linked list of 0s, 1s and 2s by changing links
- Iterative selection sort for linked list
- C Program to reverse each node value in Singly Linked List
- Select a Random Node from a Singly Linked List
- Bubble Sort for Linked List by Swapping nodes
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Insertion Sort for Singly Linked List
- Update adjacent nodes if the current node is zero in a Singly Linked List
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Recursive function to delete k-th node from linked list
- Recursive Approach to find nth node from the end in the linked list
- Recursive Selection Sort
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- In-place Merge two linked lists without changing links of first list
Improved By : andrew1234