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

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.

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

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: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

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

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.

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

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

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