Open In App
Related Articles

Javascript Program For Insertion Sort In A Singly Linked List

Improve Article
Save Article
Like Article

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.

The main step is (2.a) which has been covered in the post Sorted Insert for Singly Linked List 
Below is implementation of above algorithm:


// Javascript program to sort link list
// using insertion sort
var head = null;
var sorted = null;
class node
        this.val = val; = null;
function push(val)
    // Allocate node
    var newnode = new node(val);
    // Link the old list off the
    // new node = 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 =;
        // Insert current in sorted
        // linked list
        // Update current
        current = next;
    // Update head_ref to point to
    // sorted linked list
    head = sorted;
/* Function to insert a new_node in a Linked 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()) */
function sortedInsert(newnode)
    // Special case for the head end
    if (sorted == null ||
        sorted.val >= newnode.val)
     { = sorted;
         sorted = newnode;
         var current = sorted;
         /* Locate the node before the point
            of insertion */
         while ( != null &&
       < newnode.val)
             current =;
         } =; = newnode;
// Function to print linked list
function printlist(head)
    while (head != null)
        document.write(head.val + " ");
        head =;
// Driver code
"Linked List before Sorting..<br/>");
"<br/>LinkedList After sorting<br/>");
// This code is contributed by aashish1995


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

Time Complexity: O(n2), in the worst case, we might have to traverse all nodes of the sorted list for inserting a node, and there are “n” such nodes.

Space Complexity: O(1), no extra space is required depending on the size of the input, thus it is constant.

Please refer complete article on Insertion Sort for Singly Linked List for more details!

Last Updated : 13 Jun, 2022
Like Article
Save Article
Similar Reads
Related Tutorials