堆排序

来源:互联网 发布:c语言四则运算程序 编辑:程序博客网 时间:2024/06/08 07:22
#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) {        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--){            //如果循环到0,就是自己和自己交换            swap(data[i],data[0]);            //最值被选出到i位置            //挑出最值后,更新剩下的元素            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();    cout << heap.top() << endl;    heap.pop();    heap.output();    heap.heap_sort();    heap.output();    return 0;}
0 0