Iterative selection sort for linked list
Given a linked list, the task is to sort the linked list in non-decreasing order by using selection sort.
Examples:
Input : Linked List = 5 ->3 ->4 ->1 ->2
Output : 1 ->2 ->3 ->4 ->5Input : Linked List = 5 ->4 ->3 ->2
Output : 2 ->3 ->4 ->5
Table of Content
[Expected Approach - 1] Swapping node Values - O(n^2) Time and O(1) Space:
Approach:
The idea is to start by traversing from head node of the list. For each node, another pointer searches for the minimum value after the current node in the entire portion of the list. Once found, the minimum node's value is swapped with the current node's value. This ensures that the smallest element is positioned first in the portion, and the process repeats for the next nodes until the entire list is sorted. The algorithm performs this by comparing and swapping values rather than rearranging the node links.
// C++ program to sort a linked list
// using selection sort
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to sort the linked list using selection sort
Node* selectionSort(Node* head) {
// Traverse through the entire list
for (Node* start = head; start != nullptr;
start = start->next) {
// Assume the current start node is the minimum
Node* min_node = start;
// Find the node with the minimum data in the
// remaining unsorted part of the list
for (Node* curr = start->next; curr != nullptr;
curr = curr->next) {
if (curr->data < min_node->data) {
min_node = curr;
}
}
// Swap the data of start node and min_node
if (min_node != start) {
int node = start->data;
start->data = min_node->data;
min_node->data = node;
}
}
return head;
}
void printList(Node* node) {
Node* curr = node;
while (curr != nullptr) {
cout << " " << curr->data;
curr = curr->next;
}
}
int main() {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
Node* head = new Node(5);
head->next = new Node(3);
head->next->next = new Node(4);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(2);
head = selectionSort(head);
printList(head);
return 0;
}
// C program to sort a linked list
// using selection sort
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to sort the linked list using selection sort
struct Node* selectionSort(struct Node* head) {
// Traverse through the entire list
for (struct Node* start = head; start != NULL; start = start->next) {
// Assume the current start node is the minimum
struct Node* min_node = start;
// Find the node with the minimum data in the
// remaining unsorted part of the list
for (struct Node* curr = start->next; curr != NULL; curr = curr->next) {
if (curr->data < min_node->data) {
min_node = curr;
}
}
// Swap the data of start node and min_node
if (min_node != start) {
int node = start->data;
start->data = min_node->data;
min_node->data = node;
}
}
// Return the head of the sorted linked list
return head;
}
void printList(struct Node* node) {
struct Node* curr = node;
while (curr != NULL) {
printf(" %d", curr->data);
curr = curr->next;
}
printf("\n");
}
struct Node* createNode(int new_data) {
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
int main() {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
struct Node* head = createNode(5);
head->next = createNode(3);
head->next->next = createNode(4);
head->next->next->next = createNode(1);
head->next->next->next->next = createNode(2);
head = selectionSort(head);
printList(head);
return 0;
}
// Java program to sort a linked list using
// selection sort
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
public class GfG {
// Function to sort the linked list using
// selection sort
static Node selectionSort(Node head) {
// Traverse through the entire list
for (Node start = head; start != null;
start = start.next) {
// Assume the current start node is the minimum
Node min_node = start;
// Find the node with the minimum data in the
// remaining unsorted part of the list
for (Node curr = start.next; curr != null;
curr = curr.next) {
if (curr.data < min_node.data) {
min_node = curr;
}
}
// Swap the data of start node and min_node
if (min_node != start) {
int node = start.data;
start.data = min_node.data;
min_node.data = node;
}
}
return head;
}
static void printList(Node node) {
Node curr = node;
while (curr != null) {
System.out.print(" " + curr.data);
curr = curr.next;
}
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
Node head = new Node(5);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head = selectionSort(head);
printList(head);
}
}
# Python program to sort a linked list using selection sort
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to sort the linked list using selection sort
def selection_sort(head):
# Traverse through the entire list
start = head
while start:
# Assume the current start node is the minimum
min_node = start
# Find the node with the minimum data in the
# remaining unsorted part of the list
curr = start.next
while curr:
if curr.data < min_node.data:
min_node = curr
curr = curr.next
# Swap the data of start node and min_node
if min_node != start:
start.data, min_node.data = min_node.data, start.data
# Move to the next node
start = start.next
return head
def print_list(node):
curr = node
while curr:
print(curr.data, end=" ")
curr = curr.next
if __name__ == "__main__":
# Create a hard-coded linked list:
# 5 -> 3 -> 4 -> 1 -> 2
head = Node(5)
head.next = Node(3)
head.next.next = Node(4)
head.next.next.next = Node(1)
head.next.next.next.next = Node(2)
head = selection_sort(head)
print_list(head)
// C# program to sort a linked list using selection sort
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to sort the linked list using selection sort
static Node SelectionSort(Node head) {
// Traverse through the entire list
for (Node start = head; start != null;
start = start.next) {
// Assume the current start node is the minimum
Node minNode = start;
// Find the node with the minimum data in the
// remaining unsorted part of the list
for (Node curr = start.next; curr != null;
curr = curr.next) {
if (curr.data < minNode.data) {
minNode = curr;
}
}
// Swap the data of start node and minNode
if (minNode != start) {
int node = start.data;
start.data = minNode.data;
minNode.data = node;
}
}
return head;
}
static void PrintList(Node node) {
Node curr = node;
while (curr != null) {
Console.Write(" " + curr.data);
curr = curr.next;
}
}
static void Main() {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
Node head = new Node(5);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head = SelectionSort(head);
PrintList(head);
}
}
// JavaScript program to sort a linked list
// using selection sort
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to sort the linked list using
// selection sort
function selectionSort(head) {
let start = head;
while (start !== null) {
// Assume the current start node
// is the minimum
let minNode = start;
let curr = start.next;
// Find the node with the minimum data in the
// remaining unsorted part of the list
while (curr !== null) {
if (curr.data < minNode.data) {
minNode = curr;
}
curr = curr.next;
}
// Swap the data of start node and minNode
if (minNode !== start) {
let node = start.data;
start.data = minNode.data;
minNode.data = node;
}
start = start.next;
}
return head;
}
function printList(node) {
let curr = node;
let output = '';
while (curr !== null) {
output += ' ' + curr.data;
curr = curr.next;
}
console.log(output);
}
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
let head = new Node(5);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head = selectionSort(head);
printList(head);
Output
1 2 3 4 5
Time Complexity: O(n^2), where n is the number of nodes in the linked list.
Space Complexity: O(1)
[Expected Approach - 2] Changing node Links - O(n^2) Time and O(1) Space:
Approach:
The idea is to sort the linked list by rearranging its nodes rather than swapping their values. We start by traversing the list from the head. For each node, we maintain a pointer to find the minimum node in the remaining unsorted portion of the list. Once the minimum node is found, we detach it from its current position and link it immediately after the last node of the sorted portion. We adjust the links accordingly to maintain the list's structure. This process is repeated until all nodes are sorted, ensuring the smallest nodes are positioned first in the portion. To finalize the sorting, we reverse the sorted list to maintain the original order.This final reversal ensures that the list is correctly ordered from smallest to largest.
// C++ program to sort a linked list
// using selection sort changing links
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to sort the linked list
// using selection sort
Node* selectionSort(Node* head) {
// If the list is empty or has one element
if (head == nullptr || head->next == nullptr) {
return head;
}
Node* sorted = nullptr;
while (head != nullptr) {
Node* min_node = head;
Node* prev_min = nullptr;
Node* curr = head;
Node* prev = nullptr;
// Find the node with the minimum value
while (curr != nullptr) {
if (curr->data < min_node->data) {
min_node = curr;
prev_min = prev;
}
prev = curr;
curr = curr->next;
}
// Remove the min_node from the unsorted part
if (min_node == head) {
head = head->next;
}
else {
prev_min->next = min_node->next;
}
// Insert min_node at the beginning
// of the sorted list
min_node->next = sorted;
sorted = min_node;
}
// Reverse the sorted list to maintain
// original order
Node* prev = nullptr;
Node* curr = sorted;
while (curr != nullptr) {
Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void printList(Node* node) {
Node* curr = node;
while (curr != nullptr) {
cout << " " << curr->data;
curr = curr->next;
}
}
int main() {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
Node* head = new Node(5);
head->next = new Node(3);
head->next->next = new Node(4);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(2);
head = selectionSort(head);
printList(head);
return 0;
}
// C program to sort a linked list
// using selection sort changing links
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to sort the linked list using selection sort
struct Node* selectionSort(struct Node* head) {
// If the list is empty or has one element
if (head == NULL || head->next == NULL) {
return head;
}
struct Node* sorted = NULL;
while (head != NULL) {
struct Node* min_node = head;
struct Node* prev_min = NULL;
struct Node* curr = head;
struct Node* prev = NULL;
// Find the node with the minimum value
while (curr != NULL) {
if (curr->data < min_node->data) {
min_node = curr;
prev_min = prev;
}
prev = curr;
curr = curr->next;
}
// Remove min_node from the unsorted part
if (min_node == head) {
head = head->next;
}
else {
prev_min->next = min_node->next;
}
// Insert min_node at the
// beginning of the sorted list
min_node->next = sorted;
sorted = min_node;
}
// Reverse the sorted list to maintain
// original order
struct Node* prev = NULL;
struct Node* curr = sorted;
while (curr != NULL) {
struct Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void printList(struct Node* node) {
struct Node* curr = node;
while (curr != NULL) {
printf(" %d", curr->data);
curr = curr->next;
}
}
struct Node* createNode(int new_data) {
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
int main() {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
struct Node* head = createNode(5);
head->next = createNode(3);
head->next->next = createNode(4);
head->next->next->next = createNode(1);
head->next->next->next->next = createNode(2);
head = selectionSort(head);
printList(head);
return 0;
}
// Java program to sort a linked list using
// selection sort by changing next pointer links
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
public class GfG {
// Function to sort the linked list using
// selection sort
static Node selectionSort(Node head) {
// If the list is empty or has one element
if (head == null || head.next == null) {
return head;
}
Node sorted = null;
while (head != null) {
Node min_node = head;
Node prev_min = null;
Node curr = head;
Node prev = null;
// Find the node with the minimum value
while (curr != null) {
if (curr.data < min_node.data) {
min_node = curr;
prev_min = prev;
}
prev = curr;
curr = curr.next;
}
// Remove min_node from the unsorted part
if (min_node == head) {
head = head.next;
}
else {
prev_min.next = min_node.next;
}
// Insert min_node at the beginning
// of the sorted list
min_node.next = sorted;
sorted = min_node;
}
// Reverse the sorted list to
// maintain original order
Node prev = null;
Node curr = sorted;
while (curr != null) {
Node next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
static void printList(Node node) {
Node curr = node;
while (curr != null) {
System.out.print(" " + curr.data);
curr = curr.next;
}
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
Node head = new Node(5);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head = selectionSort(head);
printList(head);
}
}
# Python program to sort a linked list using
# selection sort by changing next pointer links
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to sort the linked list
# using selection sort
def selection_sort(head):
# If the list is empty or has one element
if not head or not head.next:
return head
sorted_list = None
while head:
min_node = head
prev_min = None
curr = head
prev = None
# Find the node with the minimum value
while curr:
if curr.data < min_node.data:
min_node = curr
prev_min = prev
prev = curr
curr = curr.next
# Remove min_node from the unsorted part
if min_node == head:
head = head.next
else:
prev_min.next = min_node.next
# Insert min_node at the beginning
# of sorted list
min_node.next = sorted_list
sorted_list = min_node
# Reverse the sorted list to maintain
# original order
prev = None
curr = sorted_list
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
def print_list(node):
curr = node
while curr:
print(curr.data, end=" ")
curr = curr.next
print()
if __name__ == "__main__":
# Create a hard-coded linked list:
# 5 -> 3 -> 4 -> 1 -> 2
head = Node(5)
head.next = Node(3)
head.next.next = Node(4)
head.next.next.next = Node(1)
head.next.next.next.next = Node(2)
head = selection_sort(head)
print_list(head)
// C# program to sort a linked list using
// selection sort by changing next pointer links
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to sort the linked list
// using selection sort
static Node SelectionSort(Node head) {
// If the list is empty or has one element
if (head == null || head.next == null) {
return head;
}
Node sorted = null;
while (head != null) {
Node minNode = head;
Node prevMin = null;
Node curr = head;
Node prev = null;
// Find the node with the minimum value
while (curr != null) {
if (curr.data < minNode.data) {
minNode = curr;
prevMin = prev;
}
prev = curr;
curr = curr.next;
}
// Remove minNode from the unsorted part
if (minNode == head) {
head = head.next;
} else {
prevMin.next = minNode.next;
}
// Insert minNode at the
// beginning of sorted list
minNode.next = sorted;
sorted = minNode;
}
// Reverse the sorted list to
// maintain original order
Node prevNode = null;
Node currNode = sorted;
while (currNode != null) {
Node nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
return prevNode;
}
static void PrintList(Node node) {
Node curr = node;
while (curr != null) {
Console.Write(" " + curr.data);
curr = curr.next;
}
Console.WriteLine();
}
static void Main() {
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
Node head = new Node(5);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head = SelectionSort(head);
PrintList(head);
}
}
// JavaScript program to sort a linked list
// using selection sort by adjusting next pointers
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to sort the linked list using
// selection sort by adjusting next pointers
function selectionSort(head) {
if (!head || !head.next) {
return head;
}
let sorted = null;
// Iterate while the head is not null
while (head !== null) {
let minNode = head;
let curr = head;
let prevMin = null;
let prev = null;
// Find the minimum node in the
// remaining unsorted list
while (curr !== null) {
if (curr.data < minNode.data) {
minNode = curr;
prevMin = prev;
}
prev = curr;
curr = curr.next;
}
// Remove minNode from the unsorted list
if (minNode === head) {
head = head.next;
}
else {
prevMin.next = minNode.next;
}
// Insert minNode at the front
// of the sorted list
minNode.next = sorted;
sorted = minNode;
}
// Reverse the sorted list to maintain
// the original order
let prevNode = null;
let currNode = sorted;
while (currNode !== null) {
let nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
return prevNode;
}
function printList(node) {
let curr = node;
let output = '';
while (curr !== null) {
output += ' ' + curr.data;
curr = curr.next;
}
console.log(output.trim());
}
// Create a hard-coded linked list:
// 5 -> 3 -> 4 -> 1 -> 2
let head = new Node(5);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head = selectionSort(head);
printList(head);
Output
1 2 3 4 5
Time Complexity: O(n^2), for each node, we traverse the remaining unsorted portion to find the minimum.
Space Complexity: O(1)