1

So we were given a problem that if given an array of n elements, we need to extract the k smallest elements from it. Our solution should use heaps and the complexity should be O(n + k log n). I think I may have figured out the solution, but I'd like to be sure about it.

I'd say that the array must first be built into a heap using a typical buildHeap() function which starts at half the length of the array and calls a minHeapify() function to ensure each parent is at least less than its children. So that would be O(n) complexity all in all. Since we need to extract k times, we would use an extractMin() function, which would remove the minimum value and minHeapify() what remains to keep a Min Heap property. The extractMin() would be O(logn), and since it would done k times, this supports the overall complexity of O(n+klogn).

Does this check out? Someone told me it should also be sorted with a heapSort() function, but this didn't make sense to me, because heapSort() would add an O(nlogn) to the overall complexity, and you're still able to extract the min without sorting...

templatetypedef
  • 328,018
  • 92
  • 813
  • 992
tsquared
  • 99
  • 2
  • 12
  • Unless I am not understanding your buildHeap and minHeapify functions, to even build a valid heap will take n*log(n) time because if an element is placed wrong, it will need average case log(n) checks to find the right place for it. – nmore Oct 09 '14 at 02:47
  • I thought this at first as well, but nearly everywhere I went kept referring to buildHeap() as O(n), and so I did quite a bit of research to figure out why. I just picked this up, so it's hard for me to explain, but heapify() won't run at any of the bottom nodes, and will run at most 1 additional time each level it progresses up (I think). Jeremy West seems to have given the best explanation of it in this thread: [link](http://stackoverflow.com/questions/9755721/build-heap-complexity) – tsquared Oct 09 '14 at 04:14
  • Nice link, I didn't know that heap building algorithm before. So yes your analysis is correct, and no you don't need to run heapSort() on an already valid heap. – nmore Oct 09 '14 at 04:18

1 Answers1

1

Yes, you are right. You don't need heapSort() but heapify() to re-order your heap.

Alex Myers
  • 4,257
  • 7
  • 17
  • 33
hey0god
  • 45
  • 9