Sort Linked List using Insertion Sort Algorithm

Difficulty: Medium, Asked-In: Microsoft, Google.

Key takeaway: An excellent problem to iterative problem solving in a linked list.

Let’s understand the problem

We have given the head of a singly linked list, write a program to sort the list using insertion sort, and return the head of the sorted linked list.

  • Suppose all elements in the linked list are unique.
  • Value can be positive, negative, or zero.

Examples

Input: [6] -> [2] -> [7] -> [4] ->NULL.
Output: [2] -> [4] -> [6] -> [7] ->NULL.

Input: [3] -> [-4] -> [-3] -> [1] -> [0] -> NULL.
Output: [-4] -> [-3] -> [0] -> [1] -> [3] -> NULL.

A short Introduction to Insertion sort on an array

To understand the implementation, we need to revise the idea of insertion sort on array.

Insertion sort adds one input to the sorted output at each step of iteration and grows partially sorted array size by 1. In other words: At each iteration, insertion sort removes one element from the input data and finds its location in the partially sorted array.

At any ith iteration, it divides the array into two parts: partially sorted part(A[0…i — 1]) and unsorted part (A[i…n-1]). So at each iteration, insertion sort picks the first element from the unsorted part, find position of that element within the sorted part and insert it there. 

Implementation of Insertion sort on linked list

We can use the same idea to implement a linked list insertion sort. But there are some key differences:

Linked list insertion sort visualization

Solution idea

We start with the unsorted linked list and loop through its nodes one by one. To insert the current node into the sorted output, we use a helper function called sortedInsert(). This function takes the head of the partially sorted list and the current node as arguments. It iterates through the list until it finds a node with a value greater than the current node.

At each iteration of the outer loop, we insert one node into its correct position in the partially sorted list. In other words, the size of the partially sorted list grows by one at each iteration.

Solution steps

  1. Initialize a pointer current to track the current element i.e. current = head.
  2. Initialize a pointer sortedHead to track the head of sorted list i.e. sortedHead = NULL
  3. Traverse the linked till current != NULL.
  4. Before inserting current node at the correct position in partially sorted list, we mark the next node using another pointer currentNext, i.e currentNext = current->next.
  5. Now we insert current node in the partially sorted part using the helper function i.e. sortedHead = sortedInsert(sortedHead, current).
  6. We move current pointer to the next node i.e. current = currentNext.
  7. By the end of loop, return the head of sorted linked list as an output.

Solution pseudocode

insertionSortLinkedList(head)
    current = head
    sortedHead = null

    while current is not null
        nextNode = current.next
        sortedHead = sortedInsert(sortedHead, current)
        current = nextNode

    return sortedHead

Implementation of helper function sortedInsert(sortedHead, current)

All the nodes before current node are sorted and our goal is to insert curr node in the partially sorted list. So we start from the head and compare each node data with data stored in curr node. 

  • When this function get called for the first node (sortedHead == NULL) or head data is greater than current node data (sortedHead->data >= current->data), we insert curr node to the front and return curr pointer as an output.

    if sortedHead is null or sortedHead.data >= current.data
      current.next = sortedHead
      return current
  • Otherwise, we run a loop to skip all the nodes less than current->data.

    temp = sortedHead
    while temp.next is not null and temp.next.data < current.data
      temp = temp.next
  • By the end of above loop, temp pointer is at the node which is just less than the current->data. In the worst case, temp may reach to the last node. Whatever be the situation, we need to insert current node to the next of temp.

    current.next = temp.next
    temp.next = current
  • Finally, we return sortedHead as an output.

Pseudocode implementation of sortedInsert()

sortedInsert(sortedHead, current)
    // Insert at the beginning if the list is empty
    // or the current value is no greater than the first value.
    if sortedHead is null or sortedHead.data >= current.data
        current.next = sortedHead
        return current

    temp = sortedHead
    // Find the insertion point.
    while temp.next is not null and temp.next.data < current.data
        temp = temp.next

    current.next = temp.next
    temp.next = current

    return sortedHead

Analysis of insertion sort on linked list

In the worst case, we need to traverse complete partially sorted list to insert a node at the correct position. Suppose i number of nodes are sorted and we want to insert (i+1)th node using the helper function. Then total number of comparison operation in the worst case = i. This is a situation of already sorted linked list.

Total count of comparison operation in the worst case = 1 + 2 + 3 + ... + n - 1 = n(n-1)/2 = O(n^2)

The best case situation occur when linked list is reverse sorted, where we need to perform one comparison operation and insert every node at the front of the linked list.

Total count of comparison operation in the best case = 1 + 1 + 1 + ... n times = n = O(n)

As we are using constant number of pointers, space complexity = O(1)

Critical ideas to think about!

  • Which is the fastest algorithm for sorting a linked list: Insertion sort, merge sort, or quicksort? Implement and compare time complexities.
  • What is the average case complexity of the above algorithm?
  • Can we think of optimizing the above code further?
  • Can we think of implementing the above algorithm recursively?
  • Insertion sort on array works in O(n) for a partially sorted array with O(n) number of inversions. Does such a benefit exist in the case of a linked list?

Another implementation without using helper function

insertionSortList(head)
    if head is null
        return head

    dummy = new ListNode(0)
    current = head
    previous = dummy

    while current is not null
        nextNode = current.next

        while previous.next is not null
              and previous.next.data < current.data
            previous = previous.next

        current.next = previous.next
        previous.next = current

        previous = dummy
        current = nextNode

    return dummy.next

Suggested problems to solve

  • Sort linked list using merge sort
  • Sort linked list using quick sort
  • Merge sort in the linked list.
  • Reverse a linked list.
  • Bubble Sort in the linked list.
  • Detect a loop in the linked list.

Enjoy learning, Enjoy algorithms!

More from EnjoyAlgorithms

Self-paced Courses and Blogs