C++堆排序
时间:2010-04-18 来源:ispexceed
#ifndef _HEAP_H
#define _HEAP_H
#include <memory.h>
class CHeap
{
public:
CHeap(int heapCapacity) : _mHeapCapacity(heapCapacity)
{
_mHeap = new int[_mHeapCapacity];
memset(_mHeap, 0, _mHeapCapacity);
}
~CHeap() { delete _mHeap; }
void BuildMaxHeap(const char *filePath);
void MaxHeapify(int i);
void HeapSort();
void PrintResult();
private:
int _mHeapSize;
int _mRealSize;
int _mHeapCapacity;
int *_mHeap;
int LeftChild(int i) { return 2 * i + 1; }
int RightChild(int i) { return 2 * (i + 1); }
void Swap(int &a, int &b) { int tmp = a; a = b; b = tmp; }
};
#endif
/*********************** Heap.cpp ***********************/
#include "Heap.h"
#include <iostream>
#include <fstream>
#include <string>
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
...
...
堆排序的算法原理很简单,但实际应用却很广泛。