Illustrate and write an algorithm For sorting a node in singly linked list

Program to sort the elements of the singly linked list

Explanation

In this program, we need to sort the nodes of the given singly linked list in ascending order.

Original list:

Illustrate and write an algorithm For sorting a node in singly linked list

Sorted list:

Illustrate and write an algorithm For sorting a node in singly linked list

To accomplish this task, we maintain two pointers: current and index. Initially, current point to head node and index will point to node next to current. Traverse through the list till current points to null, by comparing current's data with index's data. If current's data is greater than the index's data, then swap data between them. In the above example, current will initially point to 9 and index will point to 7. Since, 9 is greater than 7, swap the data. Continue this process until the entire list is sorted in ascending order.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class SortList which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail's next will point to a newly added node. This new node will become the new tail of the list.
  4. sortList() will sort the nodes of the list in ascending order.
    1. Define a node current which will point to head.
    2. Define another node index which will point to node next to current.
    3. Compare data of current and index node. If current's data is greater than the index's data then, swap the data between them.
    4. Current will point to current.next and index will point to index.next.
    5. Continue this process until the entire list is sorted.
  5. display() will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

Output:

Original list: 9 7 2 5 4 Sorted list: 2 4 5 7 9

C

Output:

Original list: 9 7 2 5 4 Sorted list: 2 4 5 7 9

JAVA

Output:

Original list: 9 7 2 5 4 Sorted list: 2 4 5 7 9

C#

Output:

Original list: 9 7 2 5 4 Sorted list: 2 4 5 7 9

PHP

Output:

Original list: 9 7 2 5 4 Sorted list: 2 4 5 7 9

Insertion Sort for Singly Linked List

We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list.
Below is a simple insertion sort algorithm for a linked list.

1) Create an empty sorted (or result) list 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3) Change head of given linked list to head of sorted (or result) list.
Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The main step is (2.a) which has been covered in the below post.
Sorted Insert for Singly Linked List

Below is implementation of above algorithm




// C program to sort link list
// using insertion sort
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
struct node* sorted = NULL;
void push(int val)
{
/* allocate node */
struct node* newnode
= (struct node*)malloc(sizeof(struct node));
newnode->data = val;
/* link the old list off the new node */
newnode->next = head;
/* move the head to point to the new node */
head = newnode;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(struct node* newnode)
{
/* Special case for the head end */
if (sorted == NULL || sorted->data >= newnode->data) {
newnode->next = sorted;
sorted = newnode;
}
else {
struct node* current = sorted;
/* Locate the node before the point of insertion
*/
while (current->next != NULL
&& current->next->data < newnode->data) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}
// function to sort a singly linked list
// using insertion sort
void insertionsort()
{
struct node* current = head;
// Traverse the given linked list and insert every
// node to sorted
while (current != NULL) {
// Store next for next iteration
struct node* next = current->next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head to point to sorted linked list
head = sorted;
}
/* Function to print linked list */
void printlist(struct node* head)
{
while (head != NULL) {
printf("%d->", head->data);
head = head->next;
}
printf("NULL");
}
// Driver program to test above functions
int main()
{
push(5);
push(20);
push(4);
push(3);
push(30);
printf("Linked List before sorting:\n");
printlist(head);
printf("\n");
insertionsort(head);
printf("Linked List after sorting:\n");
printlist(head);
}
// This code is contributed by Sornodeep Chandra




// C++ program to sort link list
// using insertion sort
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
struct Node* next;
Node(int x)
{
val = x;
next = NULL;
}
};
class LinkedlistIS {
public:
Node* head;
Node* sorted;
void push(int val)
{
/* allocate node */
Node* newnode = new Node(val);
/* link the old list off the new node */
newnode->next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly linked list using insertion
// sort
void insertionSort(Node* headref)
{
// Initialize sorted linked list
sorted = NULL;
Node* current = headref;
// Traverse the given linked list and insert every
// node to sorted
while (current != NULL) {
// Store next for next iteration
Node* next = current->next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(Node* newnode)
{
/* Special case for the head end */
if (sorted == NULL || sorted->val >= newnode->val) {
newnode->next = sorted;
sorted = newnode;
}
else {
Node* current = sorted;
/* Locate the node before the point of insertion
*/
while (current->next != NULL
&& current->next->val < newnode->val) {
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}
/* Function to print linked list */
void printlist(Node* head)
{
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
}
};
// Driver program to test above functions
int main()
{
LinkedlistIS list;
list.head = NULL;
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
cout << "Linked List before sorting" << endl;
list.printlist(list.head);
cout << endl;
list.insertionSort(list.head);
cout << "Linked List After sorting" << endl;
list.printlist(list.head);
}
// This code is contributed by nirajgusain5




// Java program to sort link list
// using insertion sort
public class LinkedlistIS
{
node head;
node sorted;
class node
{
int val;
node next;
public node(int val)
{
this.val = val;
}
}
void push(int val)
{
/* allocate node */
node newnode = new node(val);
/* link the old list off the new node */
newnode.next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly linked list using insertion sort
void insertionSort(node headref)
{
// Initialize sorted linked list
sorted = null;
node current = headref;
// Traverse the given linked list and insert every
// node to sorted
while (current != null)
{
// Store next for next iteration
node next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(node newnode)
{
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val)
{
newnode.next = sorted;
sorted = newnode;
}
else
{
node current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null && current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
/* Function to print linked list */
void printlist(node head)
{
while (head != null)
{
System.out.print(head.val + " ");
head = head.next;
}
}
// Driver program to test above functions
public static void main(String[] args)
{
LinkedlistIS list = new LinkedlistIS();
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
System.out.println("Linked List before Sorting..");
list.printlist(list.head);
list.insertionSort(list.head);
System.out.println("\nLinkedList After sorting");
list.printlist(list.head);
}
}
// This code is contributed by Rishabh Mahrsee




# Python implementation of above algorithm
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# function to sort a singly linked list using insertion sort
def insertionSort(head_ref):
# Initialize sorted linked list
sorted = None
# Traverse the given linked list and insert every
# node to sorted
current = head_ref
while (current != None):
# Store next for next iteration
next = current.next
# insert current in sorted linked list
sorted = sortedInsert(sorted, current)
# Update current
current = next
# Update head_ref to point to sorted linked list
head_ref = sorted
return head_ref
# function to insert a new_node in a list. Note that this
# function expects a pointer to head_ref as this can modify the
# head of the input linked list (similar to push())
def sortedInsert(head_ref, new_node):
current = None
# Special case for the head end */
if (head_ref == None or (head_ref).data >= new_node.data):
new_node.next = head_ref
head_ref = new_node
else:
# Locate the node before the point of insertion
current = head_ref
while (current.next != None and
current.next.data < new_node.data):
current = current.next
new_node.next = current.next
current.next = new_node
return head_ref
# BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert
# Function to print linked list */
def printList(head):
temp = head
while(temp != None):
print( temp.data, end = " ")
temp = temp.next
# A utility function to insert a node
# at the beginning of 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 off the new node
new_node.next = (head_ref)
# move the head to point to the new node
(head_ref) = new_node
return head_ref
# Driver program to test above functions
a = None
a = push(a, 5)
a = push(a, 20)
a = push(a, 4)
a = push(a, 3)
a = push(a, 30)
print("Linked List before sorting ")
printList(a)
a = insertionSort(a)
print("\nLinked List after sorting ")
printList(a)
# This code is contributed by Arnab Kundu




// C# program to sort link list
// using insertion sort
using System;
public class LinkedlistIS
{
public node head;
public node sorted;
public class node
{
public int val;
public node next;
public node(int val)
{
this.val = val;
}
}
void push(int val)
{
/* allocate node */
node newnode = new node(val);
/* link the old list off the new node */
newnode.next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly
// linked list using insertion sort
void insertionSort(node headref)
{
// Initialize sorted linked list
sorted = null;
node current = headref;
// Traverse the given
// linked list and insert every
// node to sorted
while (current != null)
{
// Store next for next iteration
node next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a list. Note that
* this function expects a pointer to head_ref as this
* can modify the head of the input linked list
* (similar to push())
*/
void sortedInsert(node newnode)
{
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val)
{
newnode.next = sorted;
sorted = newnode;
}
else
{
node current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null &&
current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
/* Function to print linked list */
void printlist(node head)
{
while (head != null)
{
Console.Write(head.val + " ");
head = head.next;
}
}
// Driver code
public static void Main(String[] args)
{
LinkedlistIS list = new LinkedlistIS();
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
Console.WriteLine("Linked List before Sorting..");
list.printlist(list.head);
list.insertionSort(list.head);
Console.WriteLine("\nLinkedList After sorting");
list.printlist(list.head);
}
}
// This code contributed by Rajput-Ji




<script>
// javascript program to sort link list
// using insertion sort
var head = null;
var sorted = null;
class node {
constructor(val) {
this.val = val;
this.next = null;
}
}
function push(val) {
/* allocate node */
var newnode = new node(val);
/* link the old list off the new node */
newnode.next = head;
/* move the head to point to the new node */
head = newnode;
}
// function to sort a singly linked list using insertion sort
function insertionSort( headref) {
// Initialize sorted linked list
var sorted = null;
var current = headref;
// Traverse the given linked list and insert every
// node to sorted
while (current != null) {
// Store next for next iteration
var next = current.next;
// insert current in sorted linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
head = sorted;
}
/*
* function to insert a new_node in a Note that this function expects a
* pointer to head_ref as this can modify the head of the input linked list
* (similar to push())
*/
function sortedInsert( newnode) {
/* Special case for the head end */
if (sorted == null || sorted.val >= newnode.val) {
newnode.next = sorted;
sorted = newnode;
} else {
var current = sorted;
/* Locate the node before the point of insertion */
while (current.next != null && current.next.val < newnode.val) {
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
/* Function to print linked list */
function printlist( head) {
while (head != null) {
document.write(head.val + " ");
head = head.next;
}
}
// Driver program to test above functions
push(5);
push(20);
push(4);
push(3);
push(30);
document.write("Linked List before Sorting..<br/>");
printlist(head);
insertionSort(head);
document.write("<br/>LinkedList After sorting<br/>");
printlist(sorted);
// This code contributed by aashish2995
</script>

Output:

Linked List before sorting 30 3 4 20 5 Linked List after sorting 3 4 5 20 30

Time and space complexity analysis:

In worst case we might have to traverse all nodes of the sorted list for inserting a node. And there are “n” such nodes.

Thus Time Complexity: O(n)*O(n)=O(n^2)

Space Complexity: No extra space is required depending on the size of the input. Thus Space complexity is constant- O(1).

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Illustrate and write an algorithm For sorting a node in singly linked list




Article Tags :
Linked List
Practice Tags :
Linked List

Merge Sort for Linked Lists

  • Difficulty Level : Hard
  • Last Updated : 26 Nov, 2021

Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.

Illustrate and write an algorithm For sorting a node in singly linked list

Let the head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so the head node has to be changed if the data at the original head is not the smallest value in the linked list.

MergeSort(headRef) 1) If the head is NULL or there is only one element in the Linked List then return. 2) Else divide the linked list into two halves. FrontBackSplit(head, &a, &b); /* a and b are two halves */ 3) Sort the two halves a and b. MergeSort(a); MergeSort(b); 4) Merge the sorted a and b (using SortedMerge() discussed here) and update the head pointer using headRef. *headRef = SortedMerge(a, b);

Linked List Operations: Traverse, Insert and Delete

In this tutorial, you will learn different operations on a linked list. Also, you will find implementation of linked list operations in C/C++, Python and Java.

There are various linked list operations that allow us to perform different actions on linked lists. For example, the insertion operation adds a new element to the linked list.

Here's a list of basic linked list operations that we will cover in this article.

  • Traversal - access each element of the linked list
  • Insertion - adds a new element to the linked list
  • Deletion - removes the existing elements
  • Search - find a node in the linked list
  • Sort - sort the nodes of the linked list

Before you learn about linked list operations in detail, make sure to know about Linked List first.

Things to Remember about Linked List

  • head points to the first node of the linked list
  • next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list.

In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:

struct node { int data; struct node *next; };

How to sort a linked list using merge sort

Merge sort is one of the most famous divide-and-conquer sorting algorithms. This algorithm can be used to sort values in any traversable data structure (i.e., a linked list).

Data Structure and Algorithms - Linked List


Advertisements

Previous Page
Next Page

A linked list is a sequence of data structures, which are connected together via links.

Linked List is a sequence of links which contains items. Each link contains a connection to another link. Linked list is the second most-used data structure after array. Following are the important terms to understand the concept of Linked List.

  • Link − Each link of a linked list can store a data called an element.

  • Next − Each link of a linked list contains a link to the next link called Next.

  • LinkedList − A Linked List contains the connection link to the first link called First.



The main step is (2.a) which has been covered in below post.
Sorted Insert for Singly Linked List

Below is implementation of above algorithm

C++

/* C program for insertion sort on a linked list */
#include<stdio.h>
#include<stdlib.h>
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
// Function to insert a given node in a sorted linked list
void sortedInsert(struct Node**,struct Node*);
// function to sort a singly linked list using insertion sort
void insertionSort(struct Node **head_ref)
{
// Initialize sorted linked list
struct Node *sorted = NULL;
// Traverse the given linked list and insert every
// node to sorted
struct Node *current = *head_ref;
while (current != NULL)
{
// Store next for next iteration
struct Node *next = current->next;
// insert current in sorted linked list
sortedInsert(&sorted, current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
*head_ref = sorted;
}
/* function to insert a new_node in a list. Note that this
function expects a pointer to head_ref as this can modify the
head of the input linked list (similar to push())*/
void sortedInsert(struct Node** head_ref,struct Node* new_node)
{
struct Node* current;
/* Special case for the head end */
if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *head_ref;
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */
/* Function to print linked list */
void printList(struct Node *head)
{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* A utility function to insert a node at the beginning of linked list */
void push(struct Node** head_ref,int new_data)
{
/* allocate node */
struct Node* new_node =new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// Driver program to test above functions
int main()
{
struct Node *a = NULL;
push(&a, 5);
push(&a, 20);
push(&a, 4);
push(&a, 3);
push(&a, 30);
printf("Linked List before sorting ");
printList(a);
insertionSort(&a);
printf(" Linked List after sorting ");
printList(a);
return 0;
}