
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Insertion Sort List C++
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]
- Related Articles
- Insertion Sort List in C++
- Insertion Sort in C#
- Insertion sort using C++ STL
- Binary Insertion Sort in C++
- C++ Program Recursive Insertion Sort
- Insertion Sort
- C++ Program to Implement Insertion Sort
- C Program for Recursive Insertion Sort
- Insertion sort in Java.
- An Insertion Sort time complexity question in C++
- Explain the insertion sort by using C language.
- Difference Between Insertion Sort and Selection Sort
- Python Program for Insertion Sort
- Insertion Sort in Python Program
- Java program to implement insertion sort

Advertisements