gpt-4-1106-preview· openai
Suzhen/CodeChat
javascript实现最大优先队列
- User
javascript实现最大优先队列
- Assistant
在JavaScript中要实现最大优先队列,你可以创建一个自定义的数据结构。一个最大优先队列中的元素不仅存储数据,还有一个关联的优先级,且这个优先级决定了它在队列中的位置。数据结构中通常都包括插入元素、删除最大元素(最高优先级元素)和查看最大元素的功能。
javascript实现最大优先队列
在JavaScript中要实现最大优先队列,你可以创建一个自定义的数据结构。一个最大优先队列中的元素不仅存储数据,还有一个关联的优先级,且这个优先级决定了它在队列中的位置。数据结构中通常都包括插入元素、删除最大元素(最高优先级元素)和查看最大元素的功能。
下面是一个基本的最大优先队列的实现:
class MaxPriorityQueue {
constructor() {
this.heap = [];
}
getParentIndex(i) {
return Math.floor((i - 1) / 2);
}
getLeftChildIndex(i) {
return 2 * i + 1;
}
getRightChildIndex(i) {
return 2 * i + 2;
}
swap(i, j) {
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
}
insert(item) {
this.heap.push(item);
this.heapifyUp();
}
heapifyUp(index = this.heap.length - 1) {
let currentIndex = index;
let parentIndex = this.getParentIndex(currentIndex);
while (currentIndex > 0 && this.heap[currentIndex] > this.heap[parentIndex]) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.getParentIndex(currentIndex);
}
}
extractMax() {
if (this.heap.length === 0) return null;
if (this.heap.length === 1) return this.heap.pop();
const max = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown();
return max;
}
heapifyDown(index = 0) {
let leftChildIndex, rightChildIndex, largestIndex, currentSize = this.heap.length;
while (true) {
leftChildIndex = this.getLeftChildIndex(index);
rightChildIndex = this.getRightChildIndex(index);
largestIndex = index;
if (leftChildIndex < currentSize && this.heap[leftChildIndex] > this.heap[largestIndex]) {
largestIndex = leftChildIndex;
}
if (rightChildIndex < currentSize && this.heap[rightChildIndex] > this.heap[largestIndex]) {
largestIndex = rightChildIndex;
}
if (largestIndex !== index) {
this.swap(index, largestIndex);
index = largestIndex;
} else {
break;
}
}
}
getMax() {
return this.heap.length > 0 ? this.heap[0] : null;
}
isEmpty() {
return this.heap.length === 0;
}
}
// 使用MaxPriorityQueue
const maxPQ = new MaxPriorityQueue();
maxPQ.insert(20);
maxPQ.insert(15);
maxPQ.insert(30);
maxPQ.insert(10);
console.log(maxPQ.extractMax()); // 30, 提取最大优先级的元素
console.log(maxPQ.getMax()); // 20, 查看最大优先级的元素,但不移除
在这个例子中,MaxPriorityQueue 类使用了一个数组来存储元素,并采用二叉堆的结构来处理最大优先队列。插入新元素时,元素被放置在数组末尾,然后通过heapifyUp方法调整其位置。当移除最大元素时,此元素通常是数组的第一个元素,随后通过heapifyDown方法将数组末尾的元素调整至合适的位置以保持二叉堆的结构。
请注意,这个实现假设存储的是数字,并简单地使用数字比较来确定优先级。在现实世界的应用中,你可能需要存储有优先级属性的对象,并相应地调整比较逻辑。