• 堆排序


    从小到大排序,建立大根堆,每次将最后一个元素与堆顶交换,此时最大元素到堆尾,堆元素-1,自上而下维护大根堆,得到的数组即从小到大

    #include<iostream>
    using namespace std;
    class Heap {
    private:
        int *data, size;
    public:
        Heap(int length_input) {
            data = new int[length_input];
            size = 0;
        }
        ~Heap() {
            delete[] data;
        }
        void push(int value) {
            data[size] = value;
            int current = size;//子节点
            int father = (current - 1) / 2;//父节点
            while (data[current] > data[father]) {
                swap(data[current], data[father]);
                current = father;
                father = (current - 1) / 2;
            }
            size++;
        }
        void output() {
            for (int i = 0; i < size; i++) {
                cout << data[i] << " ";
            }
            cout << endl;
        }
        int top() {
             return data[0];
        }
        void update(int pos, int n) {//pos当前节点 n节点数
            int lchild = 2 * pos + 1, rchild = 2 * pos + 2;
            int max_value = pos;
            if (lchild < n && data[lchild] > data[max_value]) {
                max_value = lchild;
            }
            if (rchild < n && data[rchild] > data[max_value]) {
                max_value = rchild;
            }
            if (max_value != pos) {
                swap(data[pos], data[max_value]);
                update(max_value, n);
            }
        }
        void pop() {
            swap(data[0], data[size - 1]);
            size--;
            update(0, size);
        }
        void heap_sort(){
              for(int i=size-1;i>=1;i--){
                swap(data[i],data[0]);
                 update(0, i);
        }
        }
    };
    int main() {
        int arr[10] = { 12, 9, 30, 24, 30, 4, 55, 64, 22, 37 };
        Heap heap(100);
        for (int i = 0; i < 10; i++) {
            heap.push(arr[i]);
        }
        heap.output();
        heap.heap_sort();
        heap.output();
        return 0;
    }


  • 相关阅读:
    D3D中的Alpha颜色混合(1)
    最小的MFC程序
    命名空间规则【内部】
    能登陆QQ,打不开网页
    .net重要的开源组件[更新中]
    validateRequest="false"属性及xss攻击
    RSS介绍
    Virtual、Override和New关键字的使用
    SQL语句精妙集合
    绝好的软件集合
  • 原文地址:https://www.cnblogs.com/nickqiao/p/7583358.html
Copyright © 2020-2023  润新知