问题
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