美文网首页
堆排序及C++实现PriorityQueue优先级队列

堆排序及C++实现PriorityQueue优先级队列

作者: youxiaochen | 来源:发表于2020-06-20 21:49 被阅读0次

    前言

    堆一般是由数组实现的完全二叉树,堆的排序也属于选择排序,JAVA jdk中的PriorityQueue就是采用的小根堆实现的升序排序,因此要了解PriorityQueue就必须掌握堆的排序,这里就采用大根堆方式来实现默认降序方式的PriorityQueue

    一:堆排序

    \color{red}{大根堆的概念:每个父节点的值都一定大于或等于子节点 ; 小根堆:相反每个父节点的值都一定小于或等于子节点 }

    堆排序步骤:
    1: 将无序数组构造成一个大根堆(或小根堆), 大(小)根堆的构造就是将最后一个非叶子结点到根节点进行大小调整(结点的调整从上至下)以满足大(小)根堆的概念

    直接上图(图中采用的是大根堆方式),排序无序数组 12 2 6 30 17 5 22 18


    大根堆调整.png

    从图中可以看出最后一个非叶子结点是30, 就需要依次调整 30 6 2 12结点

    2:将堆根(数组首元素)与末尾元素交换, 即相当于使数组末尾元素为最大, 再将除已经排列出的最大的尾元素前的数组继续大(小)根堆调整, 由于第一步已经排列出大(小)根堆, 此时只需要直接从根节点开始向下调整即可
    替换并调整.png
    3:代码实现(大根堆实现升序)
    class HeapSort {
    public:
        /**
         * 堆排序
         * @param arrs
         * @param len
         */
        static void sort(int *arrs, int len) {
            for (int i = (len >> 1) - 1; i >= 0; --i) {
                siftDown(arrs, len, i);
            }
            for (int i = len - 1; i > 0 ; --i) {
                swap(arrs, 0, i);
                siftDown(arrs, i, 0);
            }
        }
    
        /**
         * 从上至下调整大根堆
         * @param arrs
         * @param len
         * @param index
         */
        static void siftDown(int *arrs, int len, int index) {
            while (index < len >> 1) {
                int maxChildIndex = (index << 1) + 1; //左右孩子中找出最大值的孩子的位置
                int rightChildIndex = maxChildIndex + 1;
                if (rightChildIndex < len && arrs[rightChildIndex] > arrs[maxChildIndex]) {
                    maxChildIndex = rightChildIndex;
                }
                if (arrs[maxChildIndex] <= arrs[index]) return;
                swap(arrs, index, maxChildIndex);
                index = maxChildIndex;
            }
        }
    
        /**
         * 交换
         * @param arrs
         * @param l
         * @param r
         */
        static void swap(int *arrs, int l, int r) {
            int tmp = arrs[l];
            arrs[l] = arrs[r];
            arrs[r] = tmp;
        }
    };
    

    二:PriorityQueue降序实现

    PriorityQueue原理与堆排序类似,由于每次在队列中加入元素的时候前面的元素已经做好了大根堆调整,所以每次在队列中加入元素的时候,从下至上与父结点比较,小于父节点不做处理, 大于父节点时与父节点替换,再与父点节比较,删除节点时与堆排序的第2步一致

    直接上代码

    template <class E>
    struct Greater {
        constexpr bool operator() (const E &left, const E &right) const {
            return left > right;
        }
    };
    
    template <class E>
    struct LessEqual {
        constexpr bool operator() (const E &left, const E &right) const {
            return left <= right;
        }
    };
    
    template <class E, class C = Greater<E> >
    class PriorityQueue {
    private:
        E *queue;
        //类似JDK中的Comparable
        C comparator;
        int len = 0;
        //初始数组大小
        int capacity = 11;
        /**
         * 扩充数组
         * @param minCapacity
         */
        void grow();
        /**
         * 从下往上调整根堆
         * @param index
         * @param v
         */
        void siftUp(int index, const E &e);
        /**
         * 从上往下调整根堆
         * @param index
         * @param v
         */
        void siftDown(int index, const E &e);
    public:
        PriorityQueue();
        PriorityQueue(int capacity);
        ~PriorityQueue();
        //队列是否空
        bool isEmpty();
        /**
         * 优先队列中添加元素
         * @param e
         */
        void push(const E &e);
        /**
         * 弹出队首元素
         * @return
         */
        E poll();
        //不弹出,查看首元素
        E peek();
    };
    
    //默认大小11
    template <class E, class C>
    PriorityQueue<E, C>::PriorityQueue() : PriorityQueue(11) {
    }
    
    template <class E, class C>
    PriorityQueue<E, C>::PriorityQueue(int capacity) {
        assert(capacity > 1);
        this->capacity = capacity;
        this->queue = (E*) malloc(sizeof(E) * capacity);
    }
    
    template <class E, class C>
    PriorityQueue<E, C>::~PriorityQueue() {
        if (this->queue) {
            free(this->queue);
            this->queue = NULL;
        }
    }
    
    /**
     * 这里忽略扩充数组后大小超过int最大值
     * @tparam E
     * @tparam C
     * @param minCapacity
     */
    template <class E, class C>
    void PriorityQueue<E, C>::grow() {
        //扩充前的数组长度超过64时扩充1.5倍
        capacity = capacity + ((capacity < 64) ? (capacity + 2) : (capacity >> 1));
        queue = (E*) realloc(queue, sizeof(E) * capacity);
    }
    
    template <class E, class C>
    void PriorityQueue<E, C>::siftUp(int index, const E &e) {
        int parentIndex;
        while (index > 0) {
            parentIndex = (index - 1) >> 1;//找出父节点的位置
            if (comparator(queue[parentIndex], e)) {//父节点大于该节点,跳出循环
                break;
            }
            queue[index] = queue[parentIndex];
            index = parentIndex;
        }
        queue[index] = e;
    }
    
    template <class E, class C>
    void PriorityQueue<E, C>::siftDown(int index, const E &e) {
        while (index < len >> 1) {
            int maxChildIndex = (index << 1) + 1;//左孩子与右孩子比较得出最大孩子的位置
            int rightChildIndex = maxChildIndex + 1;
            if (rightChildIndex < len && comparator(queue[rightChildIndex], queue[maxChildIndex])) {
                maxChildIndex = rightChildIndex;
            }
            if (!comparator(queue[maxChildIndex], e)) {
                break;
            }
            queue[index] = queue[maxChildIndex];
            index = maxChildIndex;
        }
        queue[index] = e;
    }
    
    
    template <class E, class C>
    bool PriorityQueue<E, C>::isEmpty() {
        return len <= 0;
    }
    
    template <class E, class C>
    void PriorityQueue<E, C>::push(const E &e) {
        if (this->len >= capacity) {
            grow();
        }
        siftUp(this->len, e);
        this->len++;
    }
    
    template <class E, class C>
    E PriorityQueue<E, C>::poll() {
        assert(len > 0);
        E max = queue[0];
        this->len--;
        if (this->len > 0) {
            siftDown(0, queue[len]);
        }
        return max;
    }
    
    template <class E, class C>
    E PriorityQueue<E, C>::peek() {
        assert(len > 0);
        return queue[0];
    }
    
    最后附上源码https://github.com/youxiaochen/DataStructArrayLink
    数据结构看10次都不如自己动手敲一次印象深,代码中如有错误欢迎指教

    更多文章请关注:http://www.jianshu.com/u/b1cff340957c

    相关文章

      网友评论

          本文标题:堆排序及C++实现PriorityQueue优先级队列

          本文链接:https://www.haomeiwen.com/subject/idffxktx.html