Why does heap sort have a space complexity of O(1)?

前端 未结 4 1022
闹比i
闹比i 2020-12-07 22:58

I understand that both quick sort and merge sort need O(n) auxiliary space for the temporary sub-arrays that are constructed, and in-place quick sort requires <

4条回答
  •  温柔的废话
    2020-12-07 23:28

    HEAP-SORT(A)
    {
    BUILD-MAX-HEAP(A)
    if(i= A.length down to 2)
        exchange A[i] with A[1]
        A.heapSize = A.heapSize-1
        MAX-HEAPIFY(A,1)
    

    }

    i/p is stored in array which is passed to heap sort algorithm- HEAP-SORT(A). Array A is interpreted as tree and after BUILD-MAX-HEAP out of it and swapping last element with root and reducing size of heap each time by one and then call MAX-HEAPIFY(A,1) on it.

    this all operations we are performing inside that array(A) only - which is given as i/p to algorithm. we are not using any extra space while performing this operation.. So space complexity - O(1).

提交回复
热议问题