Sorting k-sorted arrays with a min heap

霸气de小男生 提交于 2020-02-03 08:12:14

问题


A good solution to sorting k-sorted arrays(each element is at most k away from its target position) is,

1) Create a Min Heap of size k+1 with first k+1 elements. This will take O(k) time. 

2) One by one remove min element from heap, put it in result array, and add a new element to heap from remaining elements.

overall complexity will be O(k) + O((n-k)*logK)

I can't understand the relevance of the array being k-sorted to using the heap technique. Won't this work even when the array is not k-sorted?


回答1:


Of course, this will not work when the array is not k-sorted.

Because the first element after sorting will always be the minimal elements among the first k+1 elements, and so on.

@leventov have shown us an example.




回答2:


A : find k smallest numbers (not necessarily sorted) from an array:
The method you think will work perfectly in O(k) + O((n-k)*logK) time .

B : sorting the array:
you find the minimum number from the heap of size k at each step , but what if the minimum number from the array is situated at index k + 2 ?
You will not be able to get it placed in 1st step of your algorithm only , till the time you insert it you would have outputted 2 numbers arguing that they are < than the original minimum .

so , you definately want to have them to be displaced by not more than k from their sorted position .



来源:https://stackoverflow.com/questions/21087139/sorting-k-sorted-arrays-with-a-min-heap

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