1. 程式人生 > 實用技巧 >大根堆程式碼實現C++

大根堆程式碼實現C++

從網上看了好多的關於大根堆建立的部落格,哎,那寫的真的是慘不忍睹,寫的真是一團稀泥。讓人越看越反胃。索性我就自己寫一下吧,本來是比較懶的,現在來看也只能自己動手豐衣足食了。

這裡需要說明一下,建立大根堆,和堆的排序演算法是兩碼事(堆的排序演算法中只是在最初的時候會用到建立大根堆,後面的就只是堆的調整)。

這兩個的共同之處就是都用到了堆的調整演算法。

我看網上有狠多的程式碼將這兩個混為一談,真的是一團稀泥。

#include <iostream>
#include<algorithm>
#include<vector>
using namespace std;
void swap(int *a, int *b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}
void adjust_heap(vector<int> &Array, int index, int len) //堆的調整
{
	int cur = index;
	int left_child = 2 *cur + 1;
		
	while(left_child <= len)
	{
	if( left_child < len && Array[left_child] < Array[left_child + 1])
	{
	     left_child++;
	}
        if(Array[cur] < Array[left_child]){
            swap(Array[cur], Array[left_child]);		
            cur = left_child;
            left_child = 2 * cur + 1;
        }
        else break;
	}
}
void make_heap(vector<int> &Array, int len)
{
	int index = (len - 2)/2 + 1;//從最後一個非葉子節點開始建堆。
	for(int i = index ; i >= 0;i--)
    adjust_heap(Array,i,len);
}
int main()
{
    vector<int>array = {2,3,2,9,0,1,0,1,2,3,9,6};
    int len = array.size() - 1;//最後一個元素的下標
    make_heap(array, len);//進行堆的建立
    for_each(array.begin(),array.end(),[](int &elem){cout<<elem<<" ";});
    cout<<endl;
    cout<<"******************"<<endl;
    for(int i = len;i > 0;i--)  //堆排序演算法的實現
    {        
        swap(array[0],array[i]);//進行元素交換
        adjust_heap(array,0,i-1);//進行堆的調整策略
        for_each(array.begin(),array.end(),[](int &elem){cout<<elem<<" ";});
        cout<<endl;
    }
	for(int i = 0; i <= len ; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
	return 0;
}

 堆排序演算法的稀泥做法就是將建立大根堆和調整大根堆放到了一起,這樣程式的冗餘量太大

下面我附上幾個錯誤的程式碼演示案例,用以警醒,和大家共勉,還有為了部落格園的好的風氣我希望大家不要在沒有一點點自己的思想的情況下去,拷貝賦值貼上別人的程式碼,然後換個標題就成了自己的程式碼了。