简体   繁体   English

优先队列问题。 在 while 循环中未定义优先级。 如何将元素排入队列?

[英]priority queue question. priority is undefined in while loop. how to enqueue element to queue?

doing a priority queue as a min-heap in javascript.在 javascript 中将优先级队列作为最小堆。 console keeps returning priority is undefined in the while loop.控制台不断返回优先级在 while 循环中未定义。 what is the problem?问题是什么? / how to enqueue element to queue? / 如何将元素排入队列?

 //min-heap class PriorityQueue { constructor(){ this.values = []; } enqueue(value, priority){ let newNode = new Node(value, priority); this.values.push(newNode); this.bubbleUp(); } bubbleUp(){ let childIndex = this.values.length - 1; let parentIndex = Math.floor((childIndex - 1) / 2); let childElement = this.values[childIndex].priority; let parentElement = this.values[parentIndex].priority; while(childElement < parentElement){ let temp = this.values[childIndex]; this.values[childIndex] = this.values[parentIndex]; this.values[parentIndex] = temp; childIndex = parentIndex; parentIndex = Math.floor((childIndex - 1) / 2); } } }

A few issues in your bubbleUp method:您的bubbleUp方法中存在一些问题:

  • The while loop never updates the variables that are compared in the loop condition. while循环从不更新循环条件中比较的变量。
  • The processing should detect when parentIndex is no longer valid, ie when childIndex is the root, and then exit.处理应该检测parentIndex何时不再有效,即childIndex是根时,然后退出。

Here is a correction:这是一个更正:

  bubbleUp(){
    let childIndex = this.values.length - 1;
    let parentIndex = Math.floor((childIndex - 1) / 2);

    while (childIndex > 0 && this.values[childIndex].priority < this.values[parentIndex].priority){
      let temp = this.values[childIndex];
      this.values[childIndex] = this.values[parentIndex];
      this.values[parentIndex] = temp;

      childIndex = parentIndex;
      parentIndex = Math.floor((childIndex - 1) / 2);
    }
  }

For full implementations, have a look at Efficient way to implement Priority Queue in Javascript?有关完整实现,请查看在 Javascript 中实现优先级队列的有效方法? , where I have also posted my preferred implementation . ,在那里我还发布了我的首选实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM