DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List

We will sort a singly link list using the bubble sort technique.

Example:

Input : 20->30->40->10

Output :10->20->30->40

Input : 20->4->3

Output : 3->4->20

Sorting Technique

The insertion sort technique works similarly in the way of playing cards technique.

The whole link list is divided into two parts. One is called sorted, and the other one is called unsorted.

Every time one node is taken from the unsorted link list and placed at its original place in the sorted link list.

C Code:

 #include <stdio.h>
 #include <stdlib.h>
 struct node {
     int val;
     struct node* next;
     struct node* prev;
 };
 void insert_beg(struct node** head, int val)
 {
     struct node* nn = (struct node*)malloc(sizeof(struct node));
     nn->val = val;
     nn->prev = NULL;
     nn->next = *head;
     if (*head == NULL) {
         *head = nn;
         return;
     }
     (*head)->prev = nn;
     *head = nn;
 }
 void insert_last(struct node** head, int val)
 {
     struct node* nn = (struct node*)malloc(sizeof(struct node));
     nn->val = val;
     nn->next = NULL;
     struct node* trav = *head;
     while (trav->next != NULL) {
         trav = trav->next;
     }
     trav->next = nn;
     nn->prev = trav;
 }
 void print(struct node* head)
 {
     struct node* trav = head;
     while (trav->next != NULL) {
         printf("%d->", trav->val);
         trav = trav->next;
     }
     printf("%d\n", trav->val);
 }
 int size(struct node* head)
 {
     struct node* trav = head;
     int c = 0;
     while (trav != NULL) {
         c++;
         trav = trav->next;
     }
     return c;
 }
 void insertion_sort(struct node** head)
 {
     struct node* i = *head;
     struct node* trav = *head;
     struct node* j;
     int n;
     if (*head != NULL && (*head)->next != NULL) {
         while (trav->next != NULL) {
             trav = trav->next;
         }
         for (i = *head; i != trav; i = i->next) {
             n = i->next->val;
             for (j = i; j != *head; j = j->prev) {
                 if (j->val > n) {
                     j->next->val = j->val;
                 }
                 else {
                     j->next->val = n;
                     break;
                 }
             }
             if (j == *head) {
                 if (j->val < n) {
                     j->next->val = n;
                 }
                 else {
                     j->next->val = j->val;
                     (*head)->val = n;
                 }
             }
         }
     }
 }
 int main()
 {
     struct node* head = NULL;
     int arr[4] = { 20, 30, 40, 10 }; // Create the link list
     printf("Before sorting: ");
 // Print list before sort
     for (int i = 0; i < 4; i++) {
         printf("%d->", arr[i]);
     }
     for (int i = 0; i < 4; i++) {
         if (head == NULL) {
             insert_beg(&head, arr[i]);
         }
         else
             insert_last(&head, arr[i]);
     }
     insertion_sort(&head); // sort the link list
     printf("\nAfter Sorting: ");
     print(head);
     return 0;
 } 

C++ Code:

 #include <bits/stdc++.h>
 #include <iostream>
 using namespace std;
 struct node {
     int data;
     node* next;
 };
 /*Function that inserts nodes in front of
     Given Linked List*/
 void InsFront(node** head, int data)
 {
     node* temp = new node;
     temp->data = data;
     temp->next = *head;
     *head = temp;
 }
 /*Function that inserts nodes in sorted order*/
 void sorted_insert(node** head, int n)
 {
     node* temp = new node;
     temp->data = n;
     if (*head == NULL || (*head)->data >= n) {
         temp->next = *head;
         *head = temp;
     }
     else {
         node* prev = *head;
         node* curr = prev->next;
         while (curr != NULL) {
             if (prev->data < n && n < curr->data) {
                 prev->next = temp;
                 temp->next = curr;
                 return;
             }
             prev = prev->next;
             curr = curr->next;
         }
         prev->next = temp;
         temp->next = curr;
     }
 }
 /*Function to apply insertion sort on list*/
 void ins_sort(node** head)
 {
     if (*head == NULL)
         return;
     node* sorted_list = NULL;
     node* curr = *head;
     while (curr != NULL) {
         sorted_insert(&sorted_list, curr->data);
         curr = curr->next;
     }
     *head = sorted_list;
 }
 void printList(node* head)
 {
     while (head != NULL) {
         cout << head->data << "-> ";
         head = head->next;
     }
 }
 /* Driver program to test above functions*/
 int main()
 {
     node* head = NULL;
 // Create the link list
     InsFront(&head, 40);
     InsFront(&head, 30);
     InsFront(&head, 10);
     InsFront(&head, 20);
     cout << "Before sorting: "; // print list before sort
     printList(head);
     /*Calling Insertion sort function*/
     ins_sort(&head); // Call insertion sort
     cout << "\nAfter sorting: ";
     printList(head); // print list after sort
     return 0;
 } 

Output:

 Before sorting: 20-> 10-> 30-> 40->
 After sorting: 10-> 20-> 30-> 40-> 

Complexities:

Worst complexity: O( n^2 )

Average complexity: O( n^2 )

Best complexity: O( n )

Space complexity: O(1)


Related Topics

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.