堆排序【Heap Sort】

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> heap{ 3,1,2,5,7,8,4,9,6 };
void Max_Heapify(vector<int> &heap, int root, int tail) {
    int FatherNode = root, &p = FatherNode;
    int lch = p * 2 + 1;
    while (lch <= tail) {
        if (lch + 1 <= tail && heap[lch] < heap[lch + 1])
            lch++;
        if (heap[p] > heap[lch])
            return;
        else {
            swap(heap[p], heap[lch]);
            p = lch;
            lch = p * 2 + 1;
        }
    }
}
void HeapSort(vector<int> &heap, int sz) {
    for (int i = sz / 2 - 1; i >= 0; --i)
        Max_Heapify(heap, i, sz - 1);
    for (int i = sz - 1; i > 0; --i) {
        swap(heap[0], heap[i]);
        Max_Heapify(heap, 0, i - 1);
    }
}
int main() {
    HeapSort(heap,(int) heap.size());
    for (int i : heap)
        cout << i << ' ';
    return 0;
}

 

posted @ 2017-03-14 21:00  codinRay  阅读(206)  评论(0编辑  收藏  举报