堆排序

来源:互联网 发布:淘宝店铺卖家版 编辑:程序博客网 时间:2024/06/18 17:10

从小到大排序,建立大根堆,每次将最后一个元素与堆顶交换,此时最大元素到堆尾,堆元素-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;}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小米手机读不出sim卡怎么办 魅蓝note6耗电快怎么办 oppo手机下载密码忘了怎么办 华为v9玩飞车卡怎么办 苹果7耳机转换器不支持怎么办 华为mate10耳机声音小怎么办 200打一年到期了怎么办 手机欠费变成2g怎么办 手机4g网用不了怎么办 手机玩王者荣耀卡怎么办 华为隐私空间密码忘记了怎么办 华为手机王者太卡怎么办 华为手机太卡怎么办呢 华为手机5x太卡!怎么办 华为手机玩游戏时太卡了怎么办? 买到华为翻新机怎么办 华为畅享8声音小怎么办 华为5a安全模式怎么办 手机跳屏怎么办金立 苹果手机触控不灵敏怎么办 华为mate8手机声音小怎么办 华为mate9相机无法对焦怎么办 新疆外地电信卡信号差怎么办 华为手机搜索不到wifi怎么办 华为浏览器恢复只有一个页面怎么办 华为手机触摸屏没反应怎么办 快递不给送上楼怎么办 华为荣耀手机声音小怎么办 华为手机来电铃声小怎么办 s弯出来时老压线怎么办 苹果7p手机弯了怎么办 小米手机摔弯了怎么办 华为畅享5没声音怎么办 掌阅语音闪退怎么办 华为mate开屏成排线怎么办 华为mate8电池坏了怎么办 8plus拍照不清晰怎么办 荣耀手环3丢了怎么办 华为mate9手机声音小怎么办 华为麦芒6丢了怎么办 华为麦芒4无法访问移动网络怎么办