So I have an assignment where I\'m giving a random list of number and I need to sort them using insertion sort. I must use a singly linked list. I looked around at other posts b
Here is the Java Implementation of Insertion Sort on Linked List:
- Time Complexity: O(n^2)
- Space Complexity: O(1) - Insertion sort is In-Place sorting algorithm
class Solution
{
public ListNode insertionSortList(ListNode head)
{
// Initialize partially sorted list
ListNode dummy = new ListNode(0), prev = dummy, current = head;
while(current != null)
{
if(prev.val > current.val)
prev = dummy;
// Find the right place to insert current node
while(prev.next != null && prev.next.val < current.val)
prev = prev.next;
// Insert current between prev and prev.next
ListNode nextNode = current.next;
current.next = prev.next;
prev.next = current;
current = nextNode;
}
return dummy.next;
}
}