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
<script>
var head = null ;
var sorted = null ;
class node
{
constructor(val)
{
this .val = val;
this .next = null ;
}
}
function push(val)
{
var newnode = new node(val);
newnode.next = head;
head = newnode;
}
function insertionSort(headref)
{
var sorted = null ;
var current = headref;
while (current != null )
{
var next = current.next;
sortedInsert(current);
current = next;
}
head = sorted;
}
function sortedInsert(newnode)
{
if (sorted == null ||
sorted.val >= newnode.val)
{
newnode.next = sorted;
sorted = newnode;
}
else
{
var current = sorted;
while (current.next != null &&
current.next.val < newnode.val)
{
current = current.next;
}
newnode.next = current.next;
current.next = newnode;
}
}
function printlist(head)
{
while (head != null )
{
document.write(head.val + " " );
head = head.next;
}
}
push(5);
push(20);
push(4);
push(3);
push(30);
document.write(
"Linked List before Sorting..<br/>" );
printlist(head);
insertionSort(head);
document.write(
"<br/>LinkedList After sorting<br/>" );
printlist(sorted);
</script>
|
Output:
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!