Insertion Sort List C++

C++Server Side ProgrammingProgramming

Suppose we have a linked list, we have to perform the insertion sort on this list. So if the list is like [9,45,23,71,80,55], sorted list is [9,23,45,55,71,80].

To solve this, we will follow these steps −

  • dummy := new Node with some random value

  • node := given list

  • while node is not null,

    • newNode = next of node, dummyHead := next of dummy, prevDummyHead := dummy

    • while true −

      • if dummyHead is not present, value of dummyHead > value of node

        • next of node := dummyHead

        • next of prevDummyHead := node

        • break the loop

      • prevDummyHead := dymmyHead, and dummyHead = next of dummy head

    • node := nextNode

  • return next of dummy

Example

Let us see the following implementation to get better understanding −

class Solution {
   public:
   ListNode* insertionSortList(ListNode* a) {
      ListNode* dummy = new ListNode(-1);
      ListNode* node = a;
      ListNode* nextNode;
      ListNode* dummyHead;
      ListNode* prevDummyHead;
      while(node != NULL){
         nextNode = node->next;
         dummyHead = dummy->next;
         prevDummyHead = dummy;
         while(1){
            if(!dummyHead || dummyHead->val > node->val){
               node->next = dummyHead;
               prevDummyHead->next = node;
               //cout << prevDummyHead->val << " " << node->val << endl;
               break;
            }
         }
         prevDummyHead = dummyHead;
         dummyHead = dummyHead->next;
      }
      node = nextNode;
   }
   return dummy->next;
}

Input

[9,45,23,71,80,55]

Output

[9,23,45,55,71,80]
raja
Published on 03-Feb-2020 15:23:31
Advertisements