优先队列默认是小顶堆吗_JS优先队列

基于数据结构中堆可实现优先队列。

优先队列满足优先级高的数据优先取出队列。

实现的优先队列满足以下功能:

1、构造函数支持传入元素比较函数,默认使用大于号进行比较。

2、支持empty(判断队列是否为空)、size(队列中元素的个数)、push(将一个元素加入队列中)、pop(取出并弹出队首元素)、top(只获得队首元素,不做弹出操作)操作。

4811f4bea13a2f3e5d2662611f063c04.png
// 优先级大的排在前面class PriorityQueue { // 构造函数,传入优先级比较函数 constructor(cmp_func) { if (cmp_func) { this._cmp_func = cmp_func } else { this._cmp_func = (a, b) => { return a > b } } this._heap = [] this._size = 0 } //获取某个节点的父节点 _parent(index) { let parent = Math.floor((index - 1) / 2); if (index > this._size - 1 || parent < 0) return null; return parent; //这里返回的 p 是在数组中的下标,数组是从0开始的 } //获取某个节点的左孩子 _leftChild(index) { let lt = 2 * index + 1; if (lt > this._size - 1) return null; return lt; } //获取某个节点的右孩子 _rightChild(index) { let rt = 2 * index + 2; if (rt > this._size - 1) return null; return rt; } //元素下沉 对下标为i的元素向下进行调整,使堆保持其性质 _downward(index) { let heap = this._heap; let lt = this._leftChild(index); let rt = this._rightChild(index); let larget = null; if (lt != null) { //左孩子为空则右孩子一定为空 if (rt == null) { larget = lt; } else { larget = this._cmp_func(heap[lt], heap[rt]) ? lt : rt; } if (this._cmp_func(heap[index], heap[larget])) { return; } else { let tmp = heap[index]; heap[index] = heap[larget]; heap[larget] = tmp; this._downward(larget) } } } //元素上浮 对下标为i的元素进行向上调整,使堆保持其性质 _upward(index) { let heap = this._heap; let parent = this._parent(index); while (index > 0 && this._cmp_func(heap[index], heap[parent])) { let tmp = heap[index]; heap[index] = heap[parent]; heap[parent] = tmp; index = parent; parent = this._parent(index); } } empty() { return this._size == 0; } size() { return this._size } push(item) { this._size += 1; if (this._heap.length >= this._size) { this._heap[this._size-1] = item; } else { this._heap.push(item) } this._upward(this._size-1); } top() { this._heap[0]; } pop() { let top_item = this._heap[0]; this._heap[0] = this._heap[this._size-1]; this._size -= 1; this._downward(0); return top_item; }}export default PriorityQueue;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值