I know how to sort a linked list using merge sort. The question is, why don't we just use a heap to create a sorted LinkedList?
- Traverse the linked list and keep adding items to a min-heap.
- Keep taking the items out of the heap and heapify the heap and add to a new result LinkedList.
step one will have O(n) for traversing the list and O(nlogn) for adding items to the heap. Total O(nlogn) [Correct me if I am wrong].
Getting an item out of heap is O(1) adding an item as the next node in a LinkedList is O(1). [Correct me if this is wrong].
So the sort can be done in O(nlogn) if my understanding is correct. This is the same as the merge sort. In terms of memory, we are using an extra heap so total memory can be O(nlogn) I assume. Merge sort can also take O(nlogn) but can be improved to O(logn).
The heap logic is the same as the "merging k sorted linked list". I am assuming each linked list has 1 item.
I might be completely wrong about my complexities on the heap version. If someone knows the exact reason why heap should not be[Why merge sort is better] used, please explain. This is not heap sort and this is not an in-place algorithm. If the time complexity is O(n²logn), I am not sure how.