0

Here is the algorithm:

void heapSort(int * arr, int startIndex, int endIndex)
{
    minHeap<int> h(endIndex + 1);

    for (int i = 0; i < endIndex + 1; i++)
        h.insert(arr[i]);

    for (int i = 0; i < endIndex + 1; i++)
        arr[i] = h.deleteAndReturnMin();
}

The methods insert() and deleteAndReturnMin() are both O(log n). endIndex + 1 can be referred to as n number of elements. So given that information, am I correct in saying the first and the second loop are both O(n log n) and thus the time complexity for the whole algorithm is O(n log n)? And to be more precise, would the total time complexity be O(2(n log n)) (not including the initializations)? I'm learning about big O notation and time complexity so I just want to make sure I'm understanding it correctly.

David Velasquez
  • 2,346
  • 1
  • 26
  • 46
  • The two is meaningless in O(2(n log n)) – Rudi Cilibrasi Jul 10 '15 at 02:22
  • For any big-oh complexity class O(c * f(n)) = O(f(n)) for all real c > 0. So we would write O(nlogn). – moreON Jul 10 '15 at 02:24
  • @moreON Thanks I get that about big O notation. I just wanted to make sure that for the sake of being more accurate if that would be correct? – David Velasquez Jul 10 '15 at 02:29
  • This answer explains why: http://stackoverflow.com/a/22188943/290617 – Mouhong Lin Jul 10 '15 at 02:30
  • It's not "more accurate" in any sense. It's exactly the same thing. – moreON Jul 10 '15 at 02:30
  • The first part where you build the heap by inserting items - thats not the normal heapsort. The normal heapsort builds the heap in-place by using a bottom-up build-heap algorithm which is O(N). It doesnt affect the overall complexity since the second part is O(n log n). And in the second part, you again do it in-place by having a max-heap , and extracting from it and shrinking it, and putting the extracted items at the end of the array. – gen-y-s Jul 10 '15 at 03:26
  • @gen-y-s: Are you sure? All the heap building algorithms I know are O(N log N). – Jonathan Leffler Jul 10 '15 at 05:27
  • @JonathanLeffler Yes I'm sure, you could look it up https://en.wikipedia.org/wiki/Heapsort – gen-y-s Jul 10 '15 at 18:12

1 Answers1

3

Your analysis is correct.

Given that the two methods you have provided are logarithmic time, your entire runtime is logarithmic time iterated over n elements O(n log n) total. You should also realize that Big-O notation ignores constant factors, so the factor of 2 is meaningless.

Note that there is a bug in your code. The inputs seem to suggest that the array starts from startIndex, but startIndex is completely ignored in the implementation.

You can fix this by changing the size of the heap to endIndex + 1 - startIndex and looping from int i = startIndex.

Strikeskids
  • 3,932
  • 13
  • 27