大根堆代码实现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;
}

 堆排序算法的稀泥做法就是将创建大根堆和调整大根堆放到了一起,这样程序的冗余量太大

 

 

下面我附上几个错误的代码演示案例,用以警醒,和大家共勉,还有为了博客园的好的风气我希望大家不要在没有一点点自己的思想的情况下去,拷贝赋值粘贴别人的代码,然后换个标题就成了自己的代码了。

posted @ 2020-08-10 18:02  LittleSwan  阅读(1785)  评论(0编辑  收藏  举报