How to Inserting Elements into a Heap in JavaScript

In this article, we will explain How to Inserting Elements into a Heap in JavaScript. A heap is a tree-like data structure. Eventually, the type of heap we will use for our objectives will be a binary tree.

Whenever a new element is inserted into a heap, it is placed next to the rightmost node of the lower layer.

If the lower layer is already full, then the leftmost node of a new layer.

Inserting Elements into a Heap in JavaScript

Previous JavaScript Articles

So, the heap’s first requirement: completeness of the tree, is ensured.

However, the pile property, which has probably been disturbed, needs to be restored.

If you want then buy a good, reliable, secure web hosting service  from here: click here

The new element is compared to its parent to move it to its correct location on the heap, and if the new element is larger than its parent, the elements are swapped.

The new element is bubbled onto the heap, while each layer is compared to its parent until finally the heap property is retrieved as below:

 swap(a, b) {
        let temp = this.heap[a];
        this.heap[a] = this.heap[b];
        this.heap[b] = temp;
    }

 insert(item) {
    this.heap.push(item);
    var index = this.heap.length - 1;
    var parent = this.parentIndex(index);
    while(this.heap[parent] && this.heap[parent] < this.heap[index]) {
        this.swap(parent, index);
        index = this.parentIndex(index);
        parent = this.parentIndex(index);
    }
}

swap() is added as a helper method to save some redundancy in our code since while inserting new elements, we may need to perform this operation several times – a number between zero and log(n).

In the case where the new element is larger than the root of the heap, we have to make it climb the entire tree which has the height of a log which in other words, is a lot.

If you want then buy a good, reliable, secure web hosting service  from here: click here

That’s it. If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.