Insertion Sort for Singly Linked List Last Updated : 07 Sep, 2024 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm.Examples:Input: 5->4->1->3->2Output: 1->2->3->4->5Input: 4->3->2->1Output: 1->2->3->4The prerequisite is Insertion Sort on Array. The idea is to gradually build a sorted portion of the list within the same memory space as the original list.Step-by-step approach:Start with an initially empty "sorted" list, which will be built by rearranging nodes from the original list.Traverse the original linked list one node at a time.For each node, find its correct position within the "sorted" portion of the list. If the node should be placed at the beginning (i.e., it's smaller than the first node in the sorted list), it becomes the new head of the sorted list.Otherwise, traverse the sorted list to find the correct position and insert the node there.Continue this process until all nodes from the original list have been repositioned in the sorted orderReturn the head of sorted list.Below is the implementation of the above approach C++ // C++ program to sort linked list // using insertion sort #include <bits/stdc++.h> using namespace std; class Node { public: int val; struct Node* next; Node(int x) { val = x; next = NULL; } }; // Function to insert a new_node in // the result list. Node* sortedInsert(Node* newnode, Node* sorted) { // Special case for the head end if (sorted == NULL || sorted->val >= newnode->val) { newnode->next = sorted; sorted = newnode; } else { Node* curr = sorted; // Locate the node before the point // of insertion while (curr->next != NULL && curr->next->val < newnode->val) { curr = curr->next; } newnode->next = curr->next; curr->next = newnode; } return sorted; } Node* insertionSort(Node* head) { // Initialize sorted linked list Node* sorted = NULL; Node* curr = head; // Traverse the given linked list and insert // every node to sorted while (curr != NULL) { // Store next for next iteration Node* next = curr->next; // Insert current in sorted linked list sorted = sortedInsert(curr, sorted); // Update current curr = next; } return sorted; } void printList(Node* curr) { while (curr != NULL) { cout << " " << curr->val; curr = curr->next; } } int main() { // Create a hard-coded linked list: // 5->4->1->3->2 Node* head = new Node(5); head->next = new Node(4); head->next->next = new Node(1); head->next->next->next = new Node(3); head->next->next->next->next = new Node(2); head = insertionSort(head); printList(head); return 0; } C // C program to sort linked list using insertion sort #include <stdio.h> #include <stdlib.h> struct Node { int val; struct Node* next; }; // Function to insert a new_node in the result list. struct Node* sortedInsert(struct Node* createNode, struct Node* sorted) { // Special case for the head end if (sorted == NULL || sorted->val >= createNode->val) { createNode->next = sorted; sorted = createNode; } else { struct Node* curr = sorted; // Locate the node before the point of insertion while (curr->next != NULL && curr->next->val < createNode->val) { curr = curr->next; } createNode->next = curr->next; curr->next = createNode; } return sorted; } struct Node* insertionSort(struct Node* head) { // Initialize sorted linked list struct Node* sorted = NULL; struct Node* curr = head; // Traverse the given linked list and insert // every node to sorted while (curr != NULL) { // Store next for next iteration struct Node* next = curr->next; // Insert current in sorted linked list sorted = sortedInsert(curr, sorted); // Update current curr = next; } return sorted; } void printList(struct Node* curr) { while (curr != NULL) { printf(" %d", curr->val); curr = curr->next; } } struct Node* createNode(int x) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->val = x; node->next = NULL; return node; } int main() { // Create a hard-coded linked list: // 5->4->1->3->2 struct Node* head = createNode(5); head->next = createNode(4); head->next->next = createNode(1); head->next->next->next = createNode(3); head->next->next->next->next = createNode(2); head = insertionSort(head); printList(head); return 0; } Java // Java program to sort linked list // using insertion sort class Node { int val; Node next; Node(int x) { val = x; next = null; } } public class GfG { // Function to insert a new_node in // the result list. static Node sortedInsert(Node newnode, Node sorted) { // Special case for the head end if (sorted == null || sorted.val >= newnode.val) { newnode.next = sorted; sorted = newnode; } else { Node curr = sorted; // Locate the node before the // point of insertion while (curr.next != null && curr.next.val < newnode.val) { curr = curr.next; } newnode.next = curr.next; curr.next = newnode; } return sorted; } static Node insertionSort(Node head) { // Initialize sorted linked list Node sorted = null; Node curr = head; // Traverse the given linked list and // insert every node to sorted while (curr != null) { // Store next for next iteration Node next = curr.next; // Insert current in sorted linked list sorted = sortedInsert(curr, sorted); // Update current curr = next; } return sorted; } static void printList(Node curr) { while (curr != null) { System.out.print(" " + curr.val); curr = curr.next; } } public static void main(String[] args) { // Create a hard-coded linked list: // 5->4->1->3->2 Node head = new Node(5); head.next = new Node(4); head.next.next = new Node(1); head.next.next.next = new Node(3); head.next.next.next.next = new Node(2); head = insertionSort(head); printList(head); } } Python # Python program to sort linked list # using insertion sort class Node: def __init__(self, x): self.val = x self.next = None def sorted_insert(newnode, sorted_head): # Special case for the head end if sorted_head is None or sorted_head.val >= newnode.val: newnode.next = sorted_head return newnode else: curr = sorted_head # Locate the node before the point of insertion while curr.next is not None and curr.next.val < newnode.val: curr = curr.next newnode.next = curr.next curr.next = newnode return sorted_head def insertion_sort(head): # Initialize sorted linked list sorted_head = None curr = head # Traverse the given linked list and # insert every node to sorted while curr is not None: next_node = curr.next # Insert current node in sorted linked list sorted_head = sorted_insert(curr, sorted_head) # Update current curr = next_node return sorted_head def print_list(curr): while curr is not None: print(f" {curr.val}", end="") curr = curr.next print() if __name__ == "__main__": # Create a hard-coded linked list: # 5->4->1->3->2 head = Node(5) head.next = Node(4) head.next.next = Node(1) head.next.next.next = Node(3) head.next.next.next.next = Node(2) head = insertion_sort(head) print_list(head) C# // C# program to sort linked list // using insertion sort using System; class Node { public int Val; public Node Next; public Node(int x) { Val = x; Next = null; } } class GfG { // Function to insert a new node in // the result list. static Node SortedInsert(Node newNode, Node sorted) { // Special case for the head end if (sorted == null || sorted.Val >= newNode.Val) { newNode.Next = sorted; sorted = newNode; } else { Node curr = sorted; // Locate the node before the // point of insertion while (curr.Next != null && curr.Next.Val < newNode.Val) { curr = curr.Next; } newNode.Next = curr.Next; curr.Next = newNode; } return sorted; } static Node InsertionSort(Node head) { // Initialize sorted linked list Node sorted = null; Node curr = head; // Traverse the given linked list and // insert every node to sorted while (curr != null) { // Store next for next iteration Node next = curr.Next; // Insert current in sorted linked list sorted = SortedInsert(curr, sorted); // Update current curr = next; } return sorted; } static void PrintList(Node curr) { while (curr != null) { Console.Write(" " + curr.Val); curr = curr.Next; } Console.WriteLine(); } static void Main() { // Create a hard-coded linked list: // 5->4->1->3->2 Node head = new Node(5); head.Next = new Node(4); head.Next.Next = new Node(1); head.Next.Next.Next = new Node(3); head.Next.Next.Next.Next = new Node(2); head = InsertionSort(head); PrintList(head); } } JavaScript // JavaScript program to sort linked list // using insertion sort class Node { constructor(val) { this.val = val; this.next = null; } } // Function to insert a new_node in // the result list. function sortedInsert(newnode, sorted) { // Special case for the head end if (sorted === null || sorted.val >= newnode.val) { newnode.next = sorted; sorted = newnode; } else { let curr = sorted; // Locate the node before // the point of insertion while (curr.next !== null && curr.next.val < newnode.val) { curr = curr.next; } newnode.next = curr.next; curr.next = newnode; } return sorted; } function insertionSort(head) { // Initialize sorted linked list let sorted = null; let curr = head; // Traverse the given linked list // and insert every node to sorted while (curr !== null) { // Store next for next iteration let next = curr.next; // Insert current in sorted linked list sorted = sortedInsert(curr, sorted); // Update current curr = next; } return sorted; } function printList(curr) { while (curr !== null) { console.log(" " + curr.val); curr = curr.next; } console.log(); } // Create a hard-coded linked list: // 5->4->1->3->2 let head = new Node(5); head.next = new Node(4); head.next.next = new Node(1); head.next.next.next = new Node(3); head.next.next.next.next = new Node(2); head = insertionSort(head); printList(head); Output 1 2 3 4 5Time Complexity: O(n2), In the worst case, we might have to traverse all nodes of the sorted list for inserting a node. Auxiliary Space: O(1), No extra space is required Comment More infoAdvertise with us Next Article Insertion sort to sort even and odd positioned elements in different orders kartik Follow Improve Article Tags : Linked List DSA Python-DSA Practice Tags : Linked List Similar Reads Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Insertion Sort in Different languagesC Program For Insertion SortInsertion sort is a simple sorting algorithm used to sort a collection of elements in a given order. It is less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort but it is simple to implement and is suitable to sort small data lists.In this article, we 4 min read C++ Program For Insertion SortInsertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array. In this article, we will learn to write a C++ 3 min read Insertion sort using C++ STLImplementation of Insertion Sort using STL functions. Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators. The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the a 1 min read Java Program for Insertion SortInsertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. In this article, we will write the program on Insertion Sort in Java.Please refer complete article on Insertion Sort for more details! Algorithm of Insertion SortThe algorithm of Insertion Sort is men 2 min read Insertion Sort - PythonInsertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list.Insertion SortThe insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the le 3 min read Binary Insertion Sort Binary insertion sort is a sorting algorithm which is similar to the insertion sort, but instead of using linear search to find the location where an element should be inserted, we use binary search. Thus, we reduce the comparative value of inserting a single element from O (N) to O (log N). It is a 15+ min read Binary Insertion Sort in Different languagesC Program for Binary Insertion SortWe can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to 5 min read Python Program for Binary Insertion SortWe can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to 3 min read Recursive Insertion Sort in Different languagesJava Program for Recursive Insertion SortInsertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.Below is an iterative algorithm for insertion sort Algorithm // Sort an arr[] of size n insertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and insert it into sorted sequence arr[0..i- 2 min read Insertion Sort on Linked ListJavascript Program For Insertion Sort In A Singly Linked ListWe 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 curr 3 min read Insertion sort to sort even and odd positioned elements in different ordersWe are given an array. We need to sort the even positioned elements in the ascending order and the odd positioned elements in the descending order. We must apply insertion sort to sort them.Examples: Input : a[] = {7, 10, 11, 3, 6, 9, 2, 13, 0} Output : 11 3 7 9 6 10 2 13 0 Even positioned elements 7 min read Sorting by combining Insertion Sort and Merge Sort algorithmsInsertion sort: The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.Advantages: Following are the advantages of insertion sort: If the size of the list to be sorted is small, insertion sort ru 2 min read Problem on Insertion SortSorting an Array in Bash using Insertion SortGiven an array, arr[] of size N, the task is to sort the array in ascending order using Insertion Sort in bash scripting. Examples: Input: arr[] = {9, 7, 2, 5}Output: 2 5 7 9Explanation: The array in sorted order is {2, 5, 7, 9} Input: arr[] = {3, 2, 1}Output: 1 2 3Explanation: The array in sorted o 2 min read Given a linked list which is sorted, how will you insert in sorted wayGiven a sorted linked list and a value to insert, write a function to insert the value in a sorted way.Initial Linked List Linked List after insertion of 9 Recommended PracticeInsert in a Sorted ListTry It! Algorithm: Let input linked list is sorted in increasing order. 1) If Linked list is empty th 14 min read Count swaps required to sort an array using Insertion SortGiven an array A[] of size N (1 ⤠N ⤠105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm.Examples:Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation:Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Coun 15 min read How to visualize selection and insertion sort using Tkinter in Python?In this article, we are going to create a GUI application that will make us visualize and understand two of the most popular sorting algorithms better, using Tkinter module.  Those two sorting algorithms are selection sort and insertion sort.  Selection sort and Insertion sort are the two most popu 6 min read Sorting algorithm visualization : Insertion SortAn algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: Generate random array and fill the pygame 3 min read Like