【JavaScript数据结构系列】04-优先队列PriorityQueue

码路工人 CoderMonkey

转载请注明作者与出处

## 1. 认识优先级队列

经典的案例场景:

  • 登机时经济舱的普通队列与头等舱的优先级队列
  • 股票交易时基于时间和价格的成交规则上,量大优先的优先级队列

再用我们打饭的例子:
假定规则:饥饿等级0级最高,需要马上进食
下图同学C优先级高于同学B,插队在同学A后面

2. 代码实现

注:

ES6 版的代码实现请查看 npm 包 data-struct-js 代码

Github/Gitee 上都能找到

npm install data-struct-js

在队列 Queue 的基础上,我们来实现一下优先级队列。

  • 优先级队列只在入队操作上与普通队列不同,其它方法相同
  • 参考上一节里的基于栈实现的队列,也稍稍修改下队列实现的代码

入队操作实现分析:

  • 在创建元素时,我们需要一个优先级参数/字段(priority)
  • 并对优先级做检查,以及默认值设置
  • 空队列时直接入队
  • 非空时,从队列头部开始比对每一个元素,新元素优先级高时插入
  • 比对到最后一个也没能插入时(新元素优先级最低)添加到队尾

主要是 enqueue 方法和 QueueElement 的封装。

// 优先队列
function PriorityQueue() {
this.__items = [] /**
*队列元素对象
*优先级默认为最低
*/
function QueueElement(element, priority) {
// check priority
if(typeof(priority) != 'number' || Number.isNaN(priority)) {
// min-level: Infinity
priority = Infinity
}
this.__element = element
// max-level: 0
this.__priority = priority QueueElement.prototype.priority = function() {
return this.__priority
} QueueElement.prototype.toString = function() {
return this.__element.toString.apply(this.__element)
}
} // 入队方法
PriorityQueue.prototype.enqueue = function(element, priority) {
var queueElement = new QueueElement(element, priority) // 空队列时直接入队
if(this.__items.length === 0) {
this.__items.push(queueElement)
}
// 非空队列入队需比较优先级
else {
var added = false
for(var i=0;i<this.__items.length;i++) {
if(queueElement.priority() < this.__items[i].priority()) {
this.__items.splice(i, 0, queueElement)
added = true
break
}
}
if(!added) {
this.__items.push(queueElement)
}
}
}
}

自己封装的优先级队列中优先级priority也可以作为复杂对象上的一个属性,无需另传参数

完整代码(用到的上一节中的 deepCopy 方法也一并贴上吧)

PriorityQueue.js

这里为了方便查看代码写全了,

实际上重复的部分可以继承普通队列

// 优先队列
function PriorityQueue() {
this.__items = [] /**
*队列元素对象
*优先级默认为最低
*/
function QueueElement(element, priority) {
// check priority
if(typeof(priority) != 'number' || Number.isNaN(priority)) {
// min-level: Infinity
priority = Infinity
}
this.__element = element
// max-level: 0
this.__priority = priority QueueElement.prototype.priority = function() {
return this.__priority
} QueueElement.prototype.toString = function() {
return this.__element.toString.apply(this.__element)
}
} // 入队方法
PriorityQueue.prototype.enqueue = function(element, priority) {
var queueElement = new QueueElement(element, priority) // 空队列时直接入队
if(this.__items.length === 0) {
this.__items.push(queueElement)
}
// 非空队列入队需比较优先级
else {
var added = false
for(var i=0;i<this.__items.length;i++) {
if(queueElement.priority() < this.__items[i].priority()) {
this.__items.splice(i, 0, queueElement)
added = true
break
}
}
if(!added) {
this.__items.push(queueElement)
}
}
} PriorityQueue.prototype.dequeue = function() {
return this.getItems().shift()
} PriorityQueue.prototype.front = function () {
return this.__items.length === 0 ? undefined : this.getItems()[0]
} PriorityQueue.prototype.getItems = function() {
return deepCopy(this.__items)
} PriorityQueue.prototype.isEmpty = function () {
return this.__items.length === 0
} PriorityQueue.prototype.size = function () {
return this.__items.length
} PriorityQueue.prototype.clear = function () {
this.__items.length = 0
} PriorityQueue.prototype.toString = function () {
var arrStr = this.__items.map((qe)=>{
return qe.toString()
})
return arrStr.join('\r\n')
}
}
function deepCopy(source) {
var dest
if(Array.isArray(source)) {
dest = []
for (let i = 0; i < source.length; i++) {
dest[i] =deepCopy(source[i])
}
}
else if(toString.call(source) === '[object Object]') {
dest = {}
for(var p in source){
if(source.hasOwnProperty(p)){
dest[p]=deepCopy(source[p])
}
}
}
else {
dest = source
}
return dest
}

测试一下

var pq = new PriorityQueue()

pq.enqueue({name: 'A-First Element | Priority:1', age: 18, toString: function(){return this.name}}, 1)
pq.enqueue({name: 'B-Second Element | Priority:3', age: 18, toString: function(){return this.name}}, 3)
pq.enqueue({name: 'C-Third Element | Priority:2', age: 18, toString: function(){return this.name}}, 2) console.log(pq.toString())

以优先级分别为 1 -> 3 -> 2 的顺序添加元素,
输出结果为:

A-First Element | Priority:1
C-Third Element | Priority:2
B-Second Element | Priority:3

收工。


做了一份 npm 工具包 data-struct-js
基于 ES6 实现的 JavaScript 数据结构,
虽然这个小轮子很少会被使用,
也许对于初学者学习 JavaScript 会有点帮助。
只要简单 install 一下即可,感兴趣的话还可以去
GitHub / Gitee 看源码。(来 Star 一个吧)

npm install data-struct-js --save-dev

https://github.com/CoderMonkie/data-struct-js

https://gitee.com/coder-monkey/data-struct-js

最后,感谢您的阅读和支持~


-end-

【JavaScript数据结构系列】04-优先队列PriorityQueue的更多相关文章

  1. 【JavaScript数据结构系列】03-队列Queue

    [JavaScript数据结构系列]03-队列Queue 码路工人 CoderMonkey 转载请注明作者与出处 1. 认识队列Queue结构 队列,跟我们的日常生活非常贴近,我们前面举例了食堂排队打 ...

  2. 【JavaScript数据结构系列】00-开篇

    [JavaScript数据结构系列]00-开篇 码路工人 CoderMonkey 转载请注明作者与出处 ## 0. 开篇[JavaScript数据结构与算法] 大的计划,写以下两部分: 1[JavaS ...

  3. JavaScript进阶系列04,函数参数个数不确定情况下的解决方案

    本篇主要体验函数参数个数不确定情况下的一个解决方案.先来看一段使用函数作为参数进行计算的实例. var calculate = function(x, y, fn) { return fn(x, y) ...

  4. 【JavaScript数据结构系列】07-循环链表CircleLinkedList

    [JavaScript数据结构系列]07-循环链表CircleLinkedList 码路工人 CoderMonkey 转载请注明作者与出处 1. 认识循环链表 首节点与尾节点相连的,就构成循环链表.其 ...

  5. 【JavaScript数据结构系列】05-链表LinkedList

    [JavaScript数据结构系列]05-链表LinkedList 码路工人 CoderMonkey 转载请注明作者与出处 ## 1. 认识链表结构(单向链表) 链表也是线性结构, 节点相连构成链表 ...

  6. 【JavaScript数据结构系列】06-双向链表DoublyLinkedList

    [JavaScript数据结构系列]06-双向链表DoublyLinkedList 码路工人 CoderMonkey 转载请注明作者与出处 1. 认识双向链表 不同于普通链表/单向链表,双向链表最突出 ...

  7. 【JavaScript数据结构系列】02-栈Stack

    [JavaScript数据结构系列]02-栈Stack 码路工人 CoderMonkey 转载请注明作者与出处 ## 1. 认识栈结构 栈是非常常用的一种数据结构,与数组同属线性数据结构,不同于数组的 ...

  8. 【JavaScript数据结构系列】01-数组Array

    [JavaScript数据结构系列]01-数组Array 码路工人 CoderMonkey 转载请注明作者与出处 # [JavaScript数据结构系列] # 01-数组Array 数组: 是有序的元 ...

  9. 算法&数据结构系列 -- 堆(优先队列)

    前言 话说新开的博客十分好用... 所以,我打算开一个坑,名曰[算法系列]. 什么意思--从名字泥应该就猜得出来... 废话不多说,进入正文~~ 正文 原理 首先,堆是一颗棵二叉树.. 其次,堆是一棵 ...

随机推荐

  1. Knapsack Problem

    0-1背包 描述:N件物品,第i件的重量是w[i],价值v[i].有一个容量为W的背包,求将哪些物品放入背包可使总价值最大.每件物品可以用0或1次. 分析:根据题意,可以写出表达式: \[max(\S ...

  2. 《新版阿里巴巴Java开发手册》提到的三目运算符的空指针问题到底是个怎么回事?

    最近,阿里巴巴Java开发手册发布了最新版--泰山版,这个名字起的不错,一览众山小. 新版新增了30+规约,其中有一条规约引起了作者的关注,那就是手册中提到在三目运算符使用过程中,需要注意自动拆箱导致 ...

  3. A Simple Problem with Integers 循环节 修改 平方 找规律 线段树

    A Simple Problem with Integers 这个题目首先要打表找规律,这个对2018取模最后都会进入一个循环节,这个循环节的打表要用到龟兔赛跑. 龟兔赛跑算法 floyed判环算法 ...

  4. openCV从入门到放弃

    与图像处理之间的关系,opencv的简介和使用定位 如题...因为偶然的机会需要用到图像处理,像我这么爱学习 并且动手能力又强的人怎么能没有心得笔记呢,哇哈哈哈.非要说的low逼点这玩意儿这玩意儿就是 ...

  5. 基于KepServer实现与S7-1200PLC之间的通信

    对于学习上位机开发,有一种通信方式是必须要了解的,那就是OPC是OLE for Process Control的简称,然而随着技术的不断发展,人们开始对它有了新的定义,比如Open Platform ...

  6. 如何将项目上传至GitHub?

    心血来潮的一天,突然想写点什么哈哈哈哈. 那就写写如何将项目上传到GitHub(矫情,上传个项目还要写个文章) 第一步:下载Git https://git-scm.com/download/win 下 ...

  7. C#黔驴技巧之去重(Distinct)

    前言 关于C#中默认的Distinct方法在什么情况下才能去重,这个就不用我再多讲,针对集合对象去重默认实现将不再满足,于是乎我们需要自定义实现来解决这个问题,接下来我们详细讲解几种常见去重方案,孰好 ...

  8. Day_08【面向对象】扩展案例3_使用多态的形式创建缉毒狗对象,调用缉毒方法和吼叫方法

    分析以下需求,并用代码实现: 1.定义动物类: 行为: 吼叫:没有具体的吼叫行为 吃饭:没有具体的吃饭行为 2.定义缉毒接口 行为: 缉毒 3.定义缉毒狗:犬的一种 行为: 吼叫:汪汪叫 吃饭:狗啃骨 ...

  9. 计算机组成及系统结构-第十章 输入输出(I/O)系统

    输入输出(I/O)系统 一.概述 1.输入输出设备的编址 2.设备控制器(I/O接口)的基本功能 3.I/O设备数据传送控制方式 二.程序中断输入输出方式 1.中断的定义 2.中断的作用 3.中断的产 ...

  10. mercurial 入门

    安装 需要python的docutils,故 sudo pip3 install docutils 然后直接安装mercurial sudo pip3 install mercurial 如果超时,则 ...