#endif
/*********************** Heap.cpp ***********************/
#include "Heap.h"
#include
#include
#include
using namespace std;
int main()
{
const char *filePath = "data.txt";
CHeap heap(20);
heap.BuildMaxHeap(filePath);
heap.HeapSort();
heap.PrintResult();
return 0;
}
void CHeap::BuildMaxHeap(const char *filePath)
{
ifstream infile(filePath);
if (infile)
{
//cout << "Open file succeed." << endl;
string line;
int i = 0;
while (infile >> line)
{
_mHeap[i] = atoi(line.c_str());
++i;
if (i > _mHeapCapacity)
break;
}
_mHeapSize = _mRealSize = i;
infile.close(); // close the file descriptor
for (i = (_mHeapSize - 2) / 2; i >= 0; --i)
{
MaxHeapify(i);
}
}
}
void CHeap::MaxHeapify(int i)
{
int left = LeftChild(i);
int right = RightChild(i);
int max = i;
if (left < _mHeapSize && _mHeap[max] < _mHeap[left])
{
max = left;
}
if (right < _mHeapSize && _mHeap[max] < _mHeap[right])
{
max = right;
}
if (max != i)
{
Swap(_mHeap[i], _mHeap[max]);
MaxHeapify(max);
}
}
void CHeap::HeapSort()
{
for (int i = _mHeapSize - 1; i > 0; --i)
{
Swap(_mHeap[0], _mHeap[i]);
--_mHeapSize;
MaxHeapify(0);
}
}
void CHeap::PrintResult()
{
cout << "Total number of digits is: " << _mRealSize << endl;
for (int i = 0; i < _mRealSize; ++i)
{
cout << _mHeap[i] << endl;
}
}
/////////////////// data.txt //////////////////
23
34
56
...
...
堆排序的算法原理很简单,但实际应用却很广泛。