c++ 堆与堆排序

1 篇文章 0 订阅
1 篇文章 0 订阅

我看了好些数据结构的书,国内的,大部分都含含糊糊的说下堆,然后列出代码,我觉得这个有点忽悠自己人了,后来是在别人的推荐下,看了《算法导论》的堆那一张,有豁然开朗的感觉,堆是一种数组对象,堆是一个父节点比子节点大(或者小)的完全二叉树,堆排序是在建立好最大堆(最小堆)的基础上实现的,实现办法是每次把根节点去掉,把最后一个元素移到根节点上,然后在调整堆形成最大堆(最小堆),再后面就是重复这个过程,直到只剩下根节点一个元素为止!

下面就是我自己是实现的代码,数组我是从索引0开始的

左子树就是:2n+1;右子树:2n+2;


#include <iostream>
#include <assert.h>
#include <fstream>
using namespace std;

template<typename T>
class maxHeap
{
public:
	maxHeap();

	~maxHeap();
	int Left(int index);//判断是否有左子树, 有则返回其索引号
	int Right(int index);//判断是否有右子树, 有则返回其索引号
	void MaxHeapIFY(int index);
	void BuildMaxHeap();
	void output();
	void heapSort();
private:
	int maxHeapSize,arrySize;
	T *heap;
	
};

template<typename T>
maxHeap<T>::maxHeap()
{
	
}

template<typename T>
maxHeap<T>::~maxHeap()
{
	if (heap)
	{
		delete[] heap;
	}
}

template<typename T>
int maxHeap<T>::Left(int index)
{
	if (2*index+1 < maxHeapSize)
	{
		return 2 * index + 1;
	}
	else
	{
		return index;
	}
}
template<typename T>
int maxHeap<T>::Right(int index)
{
	if (2 * index + 2 < maxHeapSize)
	{
		return 2 * index + 2;
	}
	else
	{
		return index;
	}
}

template<typename T>
void maxHeap<T>::MaxHeapIFY(int index)
{
	int largest = index;
	int temp;
	if (heap[index]<heap[Left(index)])
	{
		largest = Left(index);
	}
	if (heap[largest]<heap[Right(index)])
	{
		largest = Right(index);
	}
	if (largest!=index)
	{
		temp = heap[index];
		heap[index] = heap[largest];
		heap[largest] = temp;
		//递归改变变动的子树
		MaxHeapIFY(largest);
	}
}

template<typename T>
void maxHeap<T>::BuildMaxHeap()
{
	int sz = 0;
	cout << "输入要建立堆的数组大小为:"<< endl;
	cin >> sz;
	maxHeapSize = sz;
	arrySize = sz;
	heap = new T[arrySize];
	assert(heap);
	cout << "输入要建立堆的数组元素:"<<endl;
	ifstream file("1.txt");
	for (int j = 0; j < arrySize && !file.eof();j++)
	{
		file >> heap[j];
	}
	for (int k = 0; k < arrySize; k++)
	{
		cout << heap[k] << " ";
	}
	cout << endl;
	file.close();
	for (int i=(maxHeapSize-1)/2;i>=0;i--)
	{
		MaxHeapIFY(i);
	}
}

template<typename T>
void maxHeap<T>::output()
{
	if (heap)
	{
		for (int i = 0; i < arrySize;i++)
		{
			cout << heap[i] << " ";
		}
		cout << endl;
	}

}

template<typename T>
void maxHeap<T>::heapSort()
{
	for (int i = maxHeapSize-1; i > 0;i--)
	{
		if (heap)
		{
			int temp;
			temp = heap[0];
			heap[0] = heap[i];
			heap[i] = temp;
			maxHeapSize = maxHeapSize - 1;
			MaxHeapIFY(0);
		}
		
	}
}

void main()
{
	maxHeap<int> *mh = new maxHeap<int>();
	mh->BuildMaxHeap();
	cout << "最大堆结果:" << endl;
	mh->output();
	cout << "堆排序后的结果:" << endl;
	mh->heapSort();
	mh->output();
	while (1)
	{

	}
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值