堆排序(C++實現)

堆排序

大根堆

大根堆的定義爲一個完全二叉樹,且任意一個節點的值都大於它的任意一個左右孩子的值.

大根堆代碼實現

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <unordered_map>
using namespace std;
/// @brief 向下調整
void adjustdown(vector<int>&ans, int i, int len)
{
    while (true) 
    {
        int maxIndex = 2*i+1;//令左右孩子中最大的下標爲maxIndex
        if (maxIndex>len)
            break;
        if(maxIndex+1<=len&&ans[maxIndex]<ans[maxIndex+1])
            maxIndex++;
        if(ans[i]<ans[maxIndex])
        {
            swap(ans[i], ans[maxIndex]);
            i = maxIndex;
        }
        else
            break;
    }
}

/// @brief 向上調整
void adjustup(vector<int>&ans,int i)
{
    while (true) 
    {
        int parent =i%2?(i-1)/2:(i-2)/2;//父節點
        if (parent<0||ans[parent]>=ans[i])
            break;
        swap(ans[parent], ans[i]);
        i = parent;
        if(i==0)
            break;
    }
}
/// @brief 建堆
void makeheap(vector<int>&ans, int len)
{
    int i;
    i = len%2?(len-1)/2:(len-2)/2;//從第一個有孩子的節點開始調整.
    for (; i>=0&&(2*i+1)<=len; --i) 
    {
        adjustdown(ans, i,len);
    }
}

void print(vector<int>ans)
{
    for (int i=0; i<ans.size(); ++i) 
    {
        cout<<ans[i]<<" ";
    }
    cout<<endl;
}

int main()
{
    int a[]={1,2,3,19,5,28,7,-2,9,0};
    vector<int> ans(a,a+(sizeof(a)/sizeof(int)));
    int len = (int)ans.size()-1;
    makeheap(ans,len);
    while (len) 
    {
        swap(ans[len], ans[0]);
        adjustdown(ans, 0,--len);
    }
    print(ans);
    makeheap(ans,(int)ans.size()-1);
    print(ans);
    ans.push_back(8);
    adjustup(ans,(int)ans.size()-1);
    print(ans);
    return 0;
}

執行結果

-2 0 1 2 3 5 7 9 19 28 
28 19 7 9 3 5 1 -2 2 0 
28 19 7 9 8 5 1 -2 2 0 3 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章