I found a working code to insert a node at a heap implemented in array in C++ and I wonder why does the code work despite incrementing the size array

37 views Asked by At

The code I provided below is an implementation of inserting a node inside a heap (array). As to my knowledge, an array has its size defined during its initialization and can't be changed afterwards. How does this code still works, when it increments the size of the array to insert the node?

Code:

using namespace std;
int main(){
    int arr[5] =  {10,5,3,2,4};
    int n = 5;
    int key = 200;
    for(int i = 0; i<n; i++){
        cout<<arr[i]<<" ";
    }

    insertNode(arr, n, key);
    cout << n << endl;
    
    for(int i = 0; i<n; i++){
        cout<<arr[i]<<" ";
    }
    return 0;
}

void heapify(int heap[], int size, int i){
    int parent = (i-1)/2;
    if(parent >= 0){
        if(heap[parent] < heap[i]){
            swap(heap[parent], heap[i]);
            heapify(heap, size, parent);
        }
    }
}

void insertNode(int heap[], int &size, int key){
    size++;
    heap[size-1] = key;
    heapify(heap, size, size-1);
}

Output:

10 5 3 2 4 
6
200 5 10 2 4 3

I tried using this code at different C++ compilers and it still works

0

There are 0 answers