JavaScript Implementation of Min Heap

Hello! I've been working on implementing a min heap in JavaScript and I have a question about the removeMin algorithm. I am using an array to store the heap internally. When percolating downwards, I am currently using the condition 2 * k <= this.size as the stopping point. However, it doesn't feel quite right to me. Do you have any suggestions for a better stopping condition? Thank you in advance for your help!

this.removeMin = function () {
    //replace root with last element and percolate downwards
    var min = this._heap[1],
        k,
        left,
        right;

    this._heap[1] = this._heap.pop();
    this.size--;
    k = 1;

    while ( ( 2 * k ) <= this.size) {
        left = 2 * k;
        right = 2 * k + 1;

        if (this._heap[k] > this._heap[left] && this._heap[k] > this._heap[right]) {
            if (this._heap[left] <= this._heap[right]) {
                swap(this._heap, k, left);
                k = left;
            } else {
                swap(this._heap, k, right);
                k = right;
            }
        } else if (this._heap[k] > this._heap[left]) {
            swap(this._heap, k, left);
            k = left;
        } else {
            swap(this._heap, k, right);
            k = right;
        }
    }

    return min;
};

Answer №1

This is a simpler approach that may provide some assistance.

class MinHeap {
  constructor(array) {
    this.heap = this.buildHeap(array);
  }

  // O(n) time | O(1) space
  buildHeap(array) {
    const firstParentIdx = Math.floor((array.length - 2) / 2);
    for (let currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) {
      this.siftDown(currentIdx, array.length - 1, array);
    }
    return array;
  }

  // O(log(n)) time | O(1) space
  siftDown(currentIdx, endIdx, heap) {
    let childOneIdx = currentIdx * 2 + 1;
    while (childOneIdx <= endIdx) {
      const childTwoIdx = currentIdx * 2 + 2 <= endIdx ? currentIdx * 2 + 2 : -1;
      let idxToSwap;
      if (childTwoIdx !== -1 && heap[childTwoIdx] < heap[childOneIdx]) {
        idxToSwap = childTwoIdx;
      } else {
        idxToSwap = childOneIdx;
      }

      if (heap[idxToSwap] < heap[currentIdx]) {
        this.swap(currentIdx, idxToSwap, heap);
        currentIdx = idxToSwap;
        childOneIdx = currentIdx * 2 + 1;
      } else {
        return;
      }
    }
  }

  // O(log(n)) time | O(1) space
  siftUp(currentIdx, heap) {
    let parentIdx = Math.floor((currentIdx - 1) / 2);
    while (currentIdx > 0 && heap[currentIdx] < heap[parentIdx]) {
     this.swap(currentIdx, parentIdx, heap);
      currentIdx = parentIdx;
      parentIdx = Math.floor((currentIdx - 1) / 2);
    }
  }

  // O(1)  time | O(1) space
  peek() {
    return this.heap[0];
  }

  // O(log(n)) time | O(1) space
  remove() {
    this.swap(0, this.heap.length - 1, this.heap);
    const valueToRemove = this.heap.pop();
    this.siftDown(0, this.heap.length - 1, this.heap);
    return valueToRemove;
  }

  // O(log(n)) time | O(1) space
  insert(value) {
    this.heap.push(value);
    this.siftUp(this.heap.length - 1, this.heap);
  }

  swap(i, j, heap) {
    [heap[i], heap[j]] = [heap[j], heap[i]];
  }
}

Answer №2

In my opinion, it appears that there is a missing condition in the code. If the value of element k is greater than both the left and right elements, the downward movement should halt. The revised code should look like this:

   if (this._heap[k] > this._heap[left] && this._heap[k] > this._heap[right]) {
        if (this._heap[left] <= this._heap[right]) {
            swap(this._heap, k, left);
            k = left;
        } else {
            swap(this._heap, k, right);
            k = right;
        }
    } else if (this._heap[k] > this._heap[left]) {
        swap(this._heap, k, left);
        k = left;
    } else if(this._heap[k] < this._heap[right]) {
        swap(this._heap, k, right);
        k = right;
    } else {
        break;
    }

Answer №3

Avoid repetitive coding by referring to the following optimized code snippet instead of writing comparison code repeatedly. You can enhance your code by replacing it with a while loop.

.....
while (2 * k <= this.size) {
        let j = 2 * key;
        if (j < this.size && less(j, j + 1)) j++; // find smallest child
        if (!less(k, j)) break; // ensure parent is smaller than smallest child
        exch(k, j); // swap if parent is larger
        k = j; // continue until reaching the end (this.size)
    }
.....
function less(i, j){
    return this._heap[j] < this._heap[i];
}
function exch(i, j){
    let temp = this._heap[i];
    this._heap[i] = this._heap[j];
    this._heap[j] = temp;
}

Give it a try and see if it improves your code efficiency.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assign a title property in Vuejs only if the returned data from binding evaluates to true

Just starting out with vuejs and I have a question. How can I set the title based on a value returned from a specific method only if this value is true? Below is my code snippet: <td v-bind="value = getName(id)" :title="value.age" > {{value.na ...

JavaScript/DOM - What sets apart a "CSS Selector" from an attribute?

When it comes to excluding declarative event handlers: <a href='#' onclick=<handler> ... /> Is there a significant difference between an Attribute and a CSS Selector? For example, if I define my own attribute: <a href='#&a ...

The changes made to the state array in react.js are not reflected in the DOM

In my React game implementation, I have the board set up as a two-dimensional array in the initial state of the parent component. The tiles on the board are rendered by looping through this array. Each tile receives a function as a prop that allows it to m ...

Error message in node.bcrypt.js: 'No callback function provided; result is undefined.'

Currently, I am enrolled in Mosh Hamdani's Mastering React Course and have encountered some challenges with back-end development. The most recent issue is an error message stating: “undefined No callback function was given” when attempting to regi ...

Executing jQuery AJAX with PHP using 'POST' method to receive and process PHP code

Something seems to have gone wrong with my setup; it was functioning properly before but is now encountering issues. When trying to make a POST call from an HTML file to a php file (which fetches data from a REST API), instead of receiving the expected API ...

Sending an array as JSON data to PHP using the $.ajax post method. The $_POST array is

After spending a considerable amount of time on this, I'm still struggling to figure out what I'm doing wrong. I'm having difficulty retrieving the data in the PHP file. I've made multiple calls to "copy" to populate the "result" arr ...

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

Show a selection of assorted files stored in the database

router.get("/alw", function(req, res){ Product.find({"category": "alw"}, function(err, allProduct){ if (err){ console.log(err) } else { res.render("products/alw", {products ...

The JSON output from the gapi (Google Analytics) array in PHP is not displaying any values

I've been utilizing the gapi class within a CodeIgniter website. The implementation I'm using is based on this resource, which returns an array that functions perfectly. To pass this array to my JavaScript, I've been attempting the following ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

Calculating the frequency of a variable within a nested object in an Angular application

After assigning data fetched from an API to a variable called todayData, I noticed that there is a nested object named meals within it, which contains a property called name. My goal is to determine the frequency of occurrences in the name property within ...

Although my service worker's IndexedDB add() operation was successful, I am unable to view the data in the Chrome dev tools Application/Storage section

Currently running Chrome Version 57.0.2987.110 (64-bit) on MacOS/OSX 12.3 Sierra, I have recently set up a service worker, but I am relatively new to this. Now I am working on integrating an IndexedDB to store data. The service worker successfully fetch ...

Struggling to Load: Ajax Request to Google App Engine Causing Page to

I have developed a page that communicates with a Python application running on Google App Engine to retrieve JSON data using JSONP for cross-origin functionality. However, I am encountering an issue where the page hangs and fails to display the data no mat ...

What steps do I need to follow in order to properly execute this HTTP request?

Recently, I came across this amazing tool called SimplePush.io that is perfect for one of my projects. It works flawlessly via curl, as shown on their website: ~ $ curl 'https://api.simplepush.io/send/HuxgBB/Wow/So easy' or ~ $ curl --data &ap ...

How can I make a variable available on the client side by exporting it from my Node JS server built with express framework?

How can I send a variable from my Node JS server, which is built using Express, to be accessed on the client side? I need this variable to hold a value stored locally on the server and then access it in my client side JavaScript code. I discovered that ...

Obtain a fresh SQL identifier post submission through Ajax

When a comment is submitted on a post using ajax, the comment.php script will display the new comment with its own auto-incremented SQL id. It will look something like this: // The $id variable contains the SQL id after data submission <div class="comm ...

Revolutionizing user experience: New feature seamlessly triggers button actions with the power of "enter"

I need assistance with modifying a form that contains two buttons and several text inputs. Currently, if the enter key is pressed, it triggers a click event on the first button. However, I want to modify this behavior so that if any of the text boxes are f ...

Navigating through playlists on Ionic

Having just started exploring Ionic, I find myself in need of assistance with regards to navigation. I kicked off the project utilizing the sidemenus starter template which is a basic structure displaying items in a playlist using a playlist control. Howev ...

Puzzled by the unexpected error I encountered while using Node.js (require.js)

My script was running smoothly until I encountered a sudden error: undefined:3 <!DOCTYPE html> ^ SyntaxError: Unexpected token < at Object.parse (native) at Request._callback (C:\Users\Tom\Pictures&bso ...