大根堆代碼實現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;
}

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

 

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM