Search code examples
algorithmsortingheapsortspace-complexity

Difference between Auxiliary Space and Space Complexity of Heap Sort?


Difference between Auxiliary Space and Space Complexity of Heap Sort?

My attempt:

As explained here:

If we want to compare standard sorting algorithms on the basis of space, then Auxiliary Space would be a better criteria than Space Complexity. Merge Sort uses O(n) auxiliary space, Insertion sort and Heap Sort use O(1) auxiliary space. Space complexity of all these sorting algorithms is O(n) though.

I googled the space complexity of Heap Sort, I found the space complexity is O(1).

My question is:

Is that explanation correct? What is difference between Auxiliary Space and Space Complexity?


Solution

  • Auxiliary should be intended as to all the memory that is not used to store the original input.

    Heap Sort input is an array of unordered elements and it works by rearranging them in place meaning that no (or a constant amount of it i.e. not depening on the size on the input array) auxiliary space is used (the heap is built using the input array - http://www.algostructure.com/sorting/heapsort.php).

    Talking about space complexity you should also take into account the space used by the input and the auxiliary one, so in this sense, the heap sort has space complexity of O(n)+O(1) (n for the input and 1 as auxiliary space). To be fair if you want you could also consider the space used on the stack (recursive implementation of heap sort use that space, though it should be only O(logn), see here for more details).

    By the way, auxiliary space of merge-sort can also be O(1) since exists a version of merge-sort which sorts the array in place (How to sort in-place using the merge sort algorithm?).