Interview Question
Software Engineer InternsCountry: India
I tried to do it using mergesort and I think we can O(1) space complexity using mergesort but was unable to do it. Can you guide me upon that?
no, no, merge sort has O(n) space complexity! (though time is still O(n log n)).
But heapsort is in-place, i.e. O(1) space, while time is again O(n log n).
Can u provide me some link where I can find code and nice explanation about it, preferably in C++?
firstly, you can refer to the article "heapsort" on wikipedia, and then if necessary follow some references and links.
Another great source is MIT's OpenCourseWare on youtube, and especially the lecture "Heaps and Heap Sort" (.../watch?v=B7hVxCmfPtM).
I know heapsort. I can't connect it with the given question. So, plz help me how to use heapsort to sort linked list in O(1) space.
ok, I will provide my solution, but a little later.
(by the way, on wikipedia the algorithm is described using list DS, exactly your case, you can try to construct the algorithm yourself.)
Merge sort is the solution. Since this is a linked list(not a array), we don't need O(N) space. We can simply change the pointers while merging them.
Merge sort is recursive algorithm and each recursive call puts another frame on the stack.Hence It requires O(log(n)) space.
QuickSort can be performed on a linked list the same way as on regular array.
Mergesort is not O(1) space, and heapsort requires random access to items in the array to perform the operations on the heap. A random access operation would take O(n) in a linked list, which would increase the run time to (n^2 log n). Quick sort does not require random access operations, and can be done by just keeping a couple of pointers to the current scan and partition locations.
This can be done using iterative merge-sort. Merging linked lists can be done in place (constant space requirement). And recursion is avoided in the iterative version of merge-sort, by doing a bottom-up merge-sort: first merge each pair of consecutive nodes, then merge each pair of 2 nodes, then each pair of 4 nodes, etc.
- abhay0609 December 26, 2015