Heap Sort a Linked List

六月ゝ 毕业季﹏ 提交于 2020-01-06 12:41:30

问题


I'm trying to create a sort function in c++ that sorts a linked list object using Heap sort but I'm not sure how to get started. Can anyone give me any idea on how to do it ? I'm not even sure how I would sort a Linked List


回答1:


Heapsort works by building a heap out of the data. A heap is only efficient to build when you have random-access to each element.

The first step is going to be creating an array of pointers to your list objects, so you can perform the usual heap sort on the array.

The last step will be converting your array of pointers back into a linked list.

A better sorting method for a linked list is an insertion sort -- not least because you can perform the sort as part of your linked list implementation's insert() function.




回答2:


I have to agree with sarnolds answer. It is extremely inefficient to heap set a linked list for a number of reasons but the first being that they should have been sorted upon initial placement. That said, if I were going to try I would create an ArrayList<T> links the load all the links into it. Then you can grab that in heaps and sort them. Once you're finished just reload your linked list starting with thr head.




回答3:


HeapSort is good for 2 reasons -
1- It is an In place algorithm.
2- Time complexity of O(nlogn)

The O(nlogn) is because of random access nature of array, But if you use linked list then you would not get random access advantage of array. Hence the time complexity will become O(n^2). That is not good for sorting.

I will recommend you to use merge sort algo for linked list.



来源:https://stackoverflow.com/questions/8090071/heap-sort-a-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!