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