在js中实现大顶堆和小顶堆的操作(javascript)

656 阅读3分钟

堆是什么呢,在我们理解堆的过程中,可以把堆想象成一个完全二叉树,堆其实是实现优先队列的一种方式,通常在工程实践中我们会用一组一维的数据,例如数组来实现堆,但是为了方便我们理解,在我们的脑海中最好把堆想象成一个完全二叉树。

那么堆这种树结构适合处理什么问题呢,我们来看一下堆在二叉树中长什么样子

image.png

可以看到,在这棵树中,每一个节点都要比他的左右节点大,堆在树中就是长这个样子的,在工程实践中,堆比较适合用来处理需要极值的有一定顺序规律的的场景,什么是极值,就是在一组数据中需要最大/最小的值时,这时我们就可以利用堆来实现。

排序大家都不陌生,堆排序就是其中一种实现排序的方式,它利用了堆的以下特性:极值、弹出当前堆的每一个元素后,会生成一个有序的一维数据。

这其中,也分为大顶堆和小顶堆,大顶堆就是这组数据的极值是这组数据的最大值,当他弹出所有元素后,会剩下一个升序数组;小顶堆则反之,小顶堆的极值是这组数据的最小值,对这个堆进行全部弹出后,会剩下一个降序数组,数组的堆排序就是利用的大顶堆的特性,如图两个二叉树,分别是以0和1开始的一个小顶堆。

image.png

image.png

在用堆实现一个优先队列的操作时,我们会利用到一些小技巧,例如,我们对一颗完全二叉树进行层序遍历后会发现,坐标以0开头,有以下规律:
  • 当前节点的左子节点的下标 = 2 * ( 当前节点下表 ) + 1
  • 当前节点的右子节点的下标 = 2 * ( 当前节点下表 ) + 2
  • 当前节点的父节点的下标 = Math.floor(当前节点下标 / 2)

同时,坐标以0开头,有以下规律:

  • 当前节点的左子节点的下标 = 2 * ( 当前节点下表 )
  • 当前节点的右子节点的下标 = 2 * ( 当前节点下表 ) + 1
  • 当前节点的父节点的下标 = Math.floor(( 当前节点下标 - 1 ) / 2)

当我们进行push操作时,只需要把最新的元素放在树的最后一位,也是具体实现中的数组的最后一位,然后再和父节点比较。

比较时,在大顶堆中,如果当前节点比父节点大,则交换两个元素的位置;在小顶堆中则反之,如果当前节点比父节点小,则交换位置。 这样的比较要一直进行到当前的这棵树符合大顶堆和小顶堆的性质,也就是在大顶堆中,每个节点、左子节点、右子节点三个节点中必须是当前节点的值最大;在小顶堆中,每个节点、左子节点、右子节点三个节点中必须是当前节点的值最小;

接下来我们用js来实现一下大顶堆和小顶堆的操作:

大顶堆:

class HEAP {
            constructor(maxSize) {
                this.heap = new Array((typeof maxsize === 'number' && !isNaN(maxsize) ? maxsize : 1000)
                this.count = 0
            }
            push(val) {
                this.heap[this.count++] = val
                let index = this.count - 1
                while (index && this.heap[index] > this.heap[Math.floor((index - 1) / 2)]) {
                    this.swap(this.heap, index, Math.floor((index - 1) / 2))
                    index = Math.floor((index - 1) / 2)
                }
            }
            pop() {
                if (!this.size()) return
                this.swap(this.heap, 0, --this.count)
                let index = 0, last = this.count - 1
                while (index * 2 + 1 <= last) {
                    let temp = index
                    if (this.heap[temp] < this.heap[index * 2 + 1]) temp = index * 2 + 1
                    if (index * 2 + 2 <= last && this.heap[temp] < this.heap[index * 2 + 2]) temp = index * 2 + 2
                    if (temp === index) break
                    this.swap(this.heap, temp, index)
                    index = temp
                }
            }
            top() {
                return this.count ? this.heap[0] : undefined
            }
            size() {
                return this.count
            }
            swap(arr, i1, i2) {
                [arr[i1], arr[i2]] = [arr[i2], arr[i1]]
            }
        }

小顶堆:

     class HEAP {
            constructor(maxsize) {
                this.heap = new Array(typeof maxsize === 'number' && !isNaN(maxsize) ? maxsize : 1000)
                this.count = 0
            }
            size() {
                return this.count
            }
            swap(i, j) {
                [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]
            }
            push(val) {
                this.heap[this.count++] = val
                let index = this.count - 1
                while (index > 0 && this.heap[index] < this.heap[Math.floor((index - 1) / 2)]) {
                    this.swap(index, Math.floor((index - 1) / 2))
                    index = Math.floor((index - 1) / 2)
                }
            }
            pop() {
                if (this.size() === 0) return
                this.swap(0, --this.count)
                let index = 0, last = this.count - 1
                while (index * 2 + 1 <= last) {
                    let temp = index
                    if (this.heap[index * 2 + 1] < this.heap[temp]) temp = index * 2 + 1
                    if (index * 2 + 2 <= last && this.heap[index * 2 + 2] < this.heap[temp]) temp = index * 2 + 2
                    if (temp === index) break
                    this.swap(index, temp)
                    index = temp
                }
            }
            top() {
                return this.count ? this.heap[0] : undefined
            }
        }

以大顶堆为例,接下来我们来试验一下:

 const h = new HEAP(4)
        h.push(4)
        h.push(5)
        h.push(8)
        h.push(2)
        console.log(h.heap, h.top(), h.size());
        h.pop()
        h.pop()
        h.pop()
        h.pop()
        console.log(h.heap, h.top(), h.size());

输出如下:

image.png

没有问题,小顶堆也是一样的使用方法。

接下来是闲聊时间!~

毕业也一年多了,最近在好好刷刷算法,也复习复习数据结构,毕竟这些是过多少年都不会变的程序员基本功嘛,多练练总是好的,也有想过边刷题边更新心得体会,不知道能不能坚持下来哈哈哈~,欢迎大家一起交流呀!