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: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a 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 bubble sort technique...

4 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 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: 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.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

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.

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: 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.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

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.

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: 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: 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.

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: 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: 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.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.