Insertion Sort for Doubly Linked List
Sort the doubly linked list using the insertion sort technique.
Initial doubly linked list
Doubly Linked List after applying insertion sort
Below is a simple insertion sort algorithm for doubly-linked lists.
1) Create an empty sorted (or result) doubly linked list.
2) Traverse the given doubly linked list, and do the following for every node.
a) Insert the current node in a sorted way in the sorted(or result) doubly linked list.
3) Change the head of the given linked list to the head of the sorted (or result) list.
The main step is (2. a), which has been covered in the post below.
Sorted Insert for Doubly Linked List
Doubly Linked List Before Sorting 8 12 10 5 3 9 Doubly Linked List After Sorting 3 5 8 9 10 12
Time Complexity: O(n*n), as we are using a loop to traverse n times and in each traversal, we are calling the function sortedInsert which costs O(n) time (as we are traversing n time to insert the node). Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Please Login to comment...