算法导论-第六章-堆排序:基于最大堆的排序C++实现

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Heap {
private:
    int length;
    int heap_size;
    int* A;
public:
    Heap(vector<int>);
    ~Heap() { delete []A; }
    int parent(int i) { return i / 2; }
    int left(int i) { return 2 * i; }
    int right(int i) { return 2 * i + 1; }
    void max_heapify(int choice);
    void build_heap();
    void heap_sort();
};

Heap::Heap(vector<int> v) : length{static_cast<int>(v.size())}, heap_size{length} {
    A = new int[length];
    int index {};
    for_each(v.begin(), v.end(), [=](int x)mutable{ A[index++] = x; });
}

void Heap::max_heapify(int choice) {
    int left_son = left(choice);
    int right_son = right(choice);
    int largest {};
    if(left_son < heap_size && A[choice] < A[left_son]) {
        largest = left_son;
    }
    else {
        largest = choice;
    }
    if(right_son < heap_size && A[largest] < A[right_son]) {
        largest = right_son;
    }
    if(largest != choice) {
        swap(A[largest], A[choice]);
        max_heapify(largest);
    }
}

void Heap::build_heap() {
    for(int i = heap_size / 2; i >= 0; --i) {
        max_heapify(i);
    }
}

void Heap::heap_sort() {
    build_heap();
    for(int i = heap_size - 1; i >= 1; --i) {
        cout << A[0] << " ";
        swap(A[0], A[i]);
        heap_size--;
        max_heapify(0);
    }
    cout << A[0] << endl;
}

int main(int argc, const char * argv[]) {
    vector<int> v;
    int element {};
    cout << "please input the elements you want to heap_sort :" << endl;
    while(cin >> element) {
        v.push_back(element);
    }
    Heap h {v};
    cout << "the result is :" << endl;
    h.heap_sort();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值