algorithm - Why the space complexity of heapsort is `O(1)` with a recursive heapify procedure? -


when reading space complexity of merge sort, got space complexity of o(n+logn). o(logn) calculated when consider stack frame size of recursive procedures.

but heapsort utilizes recursive procedure, heapify procedure. why space complexity of heapsort o(1)?

and code reading is

```java

public class heapsort { public void buildheap(int array[]){     int length = array.length;     int heapsize = length;     int nonleaf = length / 2 - 1;     for(int = nonleaf; i>=0;i--){         heapify(array,i,heapsize);     } }  public void heapify(int array[], int i,int heapsize){     int smallest = i;     int left = 2*i+1;     int right = 2*i+2;     if(left<heapsize){         if(array[i]>array[left]){             smallest = left;         }         else smallest = i;     }     if(right<heapsize){         if(array[smallest]>array[right]){             smallest = right;         }     }     if(smallest != i){         int temp;         temp = array[i];         array[i] = array[smallest];         array[smallest] = temp;         heapify(array,smallest,heapsize);     } }  public void heapsort(int array[]){     int heapsize = array.length;     buildheap(array);      for(int i=0;i<array.length-1;i++){         // swap first , last         int temp;         temp = array[0];         array[0] = array[heapsize-1];         array[heapsize-1] = temp;         // heapify array         heapsize = heapsize - 1;         heapify(array,0,heapsize);     }    } 

```

the heapify() function can implemented tail-recursively. many functional languages guarantee tail-recursive functions use constant amount of stack space.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -