Recursive selection sort for singly linked list | Swapping node links
Last Updated :
14 Jul, 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.
Implementation:
C++
// C++ implementation of recursive selection sort
// for singly linked list | Swapping node links
#include <bits/stdc++.h>
using namespace std;
// A Linked list node
struct Node {
int data;
struct Node* next;
};
// function to swap nodes 'currX' and 'currY' in a
// linked list without swapping data
void 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 technique
struct 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 list
void 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 list
void 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 list
void printList(struct Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int 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
// Java implementation of recursive selection sort
// for singly linked list | Swapping node links
class GFG
{
// A Linked list node
static class Node
{
int data;
Node next;
};
// function to swap nodes 'currX' and 'currY' in a
// linked list without swapping data
static 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 technique
static 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 list
static 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 list
static 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 list
static void printList( Node head)
{
while (head != null)
{
System.out.print( head.data + " ");
head = head.next;
}
}
// Driver code
public 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
# Python implementation of recursive selection sort
# for singly linked list | Swapping node links
# Linked List node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# function to swap nodes 'currX' and 'currY' in a
# linked list without swapping data
def 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 technique
def 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 list
def 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 list
def 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 list
def printList( head) :
while (head != None) :
print( head.data ,end = " ")
head = head.next
# Driver code
head = None
# 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)
print( "Linked list before sorting:")
printList(head)
# sort the linked list
head = sort(head)
print( "\nLinked list after sorting:")
printList(head)
# This code is contributed by Arnab Kundu
C#
// C# implementation of recursive selection sort
// for singly linked list | Swapping node links
using System;
public class GFG
{
// A Linked list node
public class Node
{
public int data;
public Node next;
};
// function to swap nodes 'currX' and 'currY' in a
// linked list without swapping data
static 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 technique
static 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 list
static 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 list
static 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 list
static void printList( Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
// Driver code
public 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
JavaScript
<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>
OutputLinked list before sorting:n10 12 8 4 6
Linked list after sorting:n4 6 8 10 12
Time Complexity: O(n2)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem