Heap sort for Linked List
Given a linked list, the task is to sort the linked list using HeapSort.
Input: list = 7 -> 698147078 -> 1123629290 -> 1849873707 -> 1608878378 -> 140264035 -> -1206302000
Output: -1206302000 -> 7 -> 140264035 -> 1123629290 -> 1608878378 -> 1698147078 ->1849873707
Input: list = 7 -> -1075222361 -> -1602192039 -> -1374886644 -> -1007110694 -> -95856765 -> -1739971780
Output: -1739971780 -> -1602192039 -> -1374886644 -> -1075222361 -> -1007110694 -> -95856765 -> 7
Approach: The idea to solve the problem using HeapSort is as follows:
Create an array of Node type from LinkedList and use the heapsort method as applied for normal arrays. The only difference is the usage of custom comparator for comparing the Nodes.
Follow the steps to solve the problem:
- Copy the Node data of the linked list to an array of Node type.
- Now use this array as source and sort the data using heapsort as applied in case of array.
- Use custom comparator to compare the Nodes.
- Since Node based array is being used, the data change effect will actually be on LinkedList but not on the array.
- Finally, print the data of the linked list.
Below is the implementation of the above approach:
LinkedList before sorting: 7 -126832807 1771004780 1641683278 -179100326 -311811843 1468066971 LinkedList after sorting: -311811843 -179100326 -126832807 7 1468066971 1641683278 1771004780
Time Complexity: O(N * logN), where N is the number of nodes in the given LinkedList.
Auxiliary Space: O(N), for creating an additional array to store the given nodes.
Please Login to comment...