📜  Javascript中优先队列的实现

📅  最后修改于: 2022-05-13 01:58:10.537000             🧑  作者: Mango

Javascript中优先队列的实现

Priority Queue 是 Queue 的扩展,具有以下一些属性:

  1. 优先级队列的每个元素都有一个与之关联的优先级。
  2. 根据优先级将元素添加到队列中。
  3. 最低优先级的元素首先被删除。

我们可以使用两种方法设计一个优先级队列,在第一种情况下,我们可以在队列末尾添加队列元素,我们可以根据优先级删除队列中的元素。在第二种情况下,我们可以根据优先级将元素添加到队列中,并从队列的最前面移除它们。在本文中,我们将使用第二种方法来实现优先级队列。

注意:假设优先级队列可以动态增长,我们不考虑溢出情况。

让我们看一个优先队列类的例子:

例子:

Javascript
// User defined class
// to store element and its priority
class QElement {
    constructor(element, priority)
    {
        this.element = element;
        this.priority = priority;
    }
}
 
// PriorityQueue class
class PriorityQueue {
 
    // An array is used to implement priority
    constructor()
    {
        this.items = [];
    }
 
    // functions to be implemented
    // enqueue(item, priority)
    // dequeue()
    // front()
    // isEmpty()
    // printPQueue()
}


Javascript
// enqueue function to add element
// to the queue as per priority
enqueue(element, priority)
{
    // creating object from queue element
    var qElement = new QElement(element, priority);
    var contain = false;
 
    // iterating through the entire
    // item array to add element at the
    // correct location of the Queue
    for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].priority > qElement.priority) {
            // Once the correct location is found it is
            // enqueued
            this.items.splice(i, 0, qElement);
            contain = true;
            break;
        }
    }
 
    // if the element have the highest priority
    // it is added at the end of the queue
    if (!contain) {
        this.items.push(qElement);
    }
}


Javascript
// dequeue method to remove
// element from the queue
dequeue()
{
    // return the dequeued element
    // and remove it.
    // if the queue is empty
    // returns Underflow
    if (this.isEmpty())
        return "Underflow";
    return this.items.shift();
}


Javascript
// front function
front()
{
    // returns the highest priority element
    // in the Priority queue without removing it.
    if (this.isEmpty())
        return "No elements in Queue";
    return this.items[0];
}


Javascript
// rear function
rear()
{
    // returns the lowest priority
    // element of the queue
    if (this.isEmpty())
        return "No elements in Queue";
    return this.items[this.items.length - 1];
}


Javascript
// isEmpty function
isEmpty()
{
    // return true if the queue is empty.
    return this.items.length == 0;
}


Javascript
// printQueue function
// prints all the element of the queue
printPQueue()
{
    var str = "";
    for (var i = 0; i < this.items.length; i++)
        str += this.items[i].element + " ";
    return str;
}


Javascript
// creating object for queue class
var priorityQueue = new PriorityQueue();
 
// testing isEmpty and front on an empty queue
// return true
console.log(priorityQueue.isEmpty());
 
// returns "No elements in Queue"
console.log(priorityQueue.front());
 
// adding elements to the queue
priorityQueue.enqueue("Sumit", 2);
priorityQueue.enqueue("Gourav", 1);
priorityQueue.enqueue("Piyush", 1);
priorityQueue.enqueue("Sunny", 2);
priorityQueue.enqueue("Sheru", 3);
 
// prints [Gourav Piyush Sumit Sunny Sheru]
console.log(priorityQueue.printPQueue());
 
// prints Gourav
console.log(priorityQueue.front().element);
 
// pritns Sheru
console.log(priorityQueue.rear().element);
 
// removes Gouurav
// priorityQueue contains
// [Piyush Sumit Sunny Sheru]
console.log(priorityQueue.dequeue().element);
 
// Adding another element to the queue
priorityQueue.enqueue("Sunil", 2);
 
// prints [Piyush Sumit Sunny Sunil Sheru]
console.log(priorityQueue.printPQueue());


正如您在上面的示例中看到的,我们已经定义了PriorityQueue类的骨架。我们使用了一个用户定义的类QElement有两个属性 元素和优先级。我们在 PriorityQueue 类中使用了一个数组来实现优先队列,这个数组是 QElement 的容器。

1. enqueue() – 根据优先级将元素添加到队列中。

Javascript

// enqueue function to add element
// to the queue as per priority
enqueue(element, priority)
{
    // creating object from queue element
    var qElement = new QElement(element, priority);
    var contain = false;
 
    // iterating through the entire
    // item array to add element at the
    // correct location of the Queue
    for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].priority > qElement.priority) {
            // Once the correct location is found it is
            // enqueued
            this.items.splice(i, 0, qElement);
            contain = true;
            break;
        }
    }
 
    // if the element have the highest priority
    // it is added at the end of the queue
    if (!contain) {
        this.items.push(qElement);
    }
}

在这个方法中,我们创建了一个具有属性elementpriorityqElement 。然后我们遍历队列,根据优先级找到qElement的正确位置并添加。

2. dequeue() – 从优先队列中移除一个元素

Javascript

// dequeue method to remove
// element from the queue
dequeue()
{
    // return the dequeued element
    // and remove it.
    // if the queue is empty
    // returns Underflow
    if (this.isEmpty())
        return "Underflow";
    return this.items.shift();
}

此函数从队列的前面删除一个元素,因为最高优先级的元素存储在优先级队列的前面。我们已经使用数组的 shift 方法从队列中移除一个元素。

3.front() ——返回优先队列的最前面的元素

Javascript

// front function
front()
{
    // returns the highest priority element
    // in the Priority queue without removing it.
    if (this.isEmpty())
        return "No elements in Queue";
    return this.items[0];
}

该函数返回优先级队列的最前面的元素。我们只需返回数组的第 0 个元素即可获得优先级队列的前面。

4.rear() ——返回优先级队列的最后一个元素

Javascript

// rear function
rear()
{
    // returns the lowest priority
    // element of the queue
    if (this.isEmpty())
        return "No elements in Queue";
    return this.items[this.items.length - 1];
}

此函数返回队列的最后一个元素或最低优先级元素。

辅助方法:
让我们声明一些在处理优先级队列时非常有用的辅助方法。

1. isEmpty() – 如果优先队列为空,则返回 true

Javascript

// isEmpty function
isEmpty()
{
    // return true if the queue is empty.
    return this.items.length == 0;
}

我们使用数组的长度属性来获取长度,如果它为 0,则优先级队列为空。

2. printPQueue() - 它按照从高到低的优先级打印队列的元素

Javascript

// printQueue function
// prints all the element of the queue
printPQueue()
{
    var str = "";
    for (var i = 0; i < this.items.length; i++)
        str += this.items[i].element + " ";
    return str;
}

在这个方法中,我们将每个优先队列项的元素属性连接成一个字符串。

注意:-这里我们将“1”视为最高优先级元素,您可以根据需要进行修改。

执行
现在让我们使用这个优先队列类及其上面描述的不同方法

Javascript

// creating object for queue class
var priorityQueue = new PriorityQueue();
 
// testing isEmpty and front on an empty queue
// return true
console.log(priorityQueue.isEmpty());
 
// returns "No elements in Queue"
console.log(priorityQueue.front());
 
// adding elements to the queue
priorityQueue.enqueue("Sumit", 2);
priorityQueue.enqueue("Gourav", 1);
priorityQueue.enqueue("Piyush", 1);
priorityQueue.enqueue("Sunny", 2);
priorityQueue.enqueue("Sheru", 3);
 
// prints [Gourav Piyush Sumit Sunny Sheru]
console.log(priorityQueue.printPQueue());
 
// prints Gourav
console.log(priorityQueue.front().element);
 
// pritns Sheru
console.log(priorityQueue.rear().element);
 
// removes Gouurav
// priorityQueue contains
// [Piyush Sumit Sunny Sheru]
console.log(priorityQueue.dequeue().element);
 
// Adding another element to the queue
priorityQueue.enqueue("Sunil", 2);
 
// prints [Piyush Sumit Sunny Sunil Sheru]
console.log(priorityQueue.printPQueue());