今天看了第六章的堆排序,故将其用C++实现,具体代码如下:
Heap.h
#pragma once
class CHeap
{
public:
CHeap(int * p = NULL,int n = 0);
CHeap(const CHeap&);
CHeap& operator= (const CHeap&);
void Max_Heaprity(int index,const int size);
void Build_MaxHeap();
void HeapSort();
void Output();
public:
~CHeap(void);
private:
int *m_pIntArr;
int m_heapSize;
};
Heap.cpp
#include "StdAfx.h"
#include "Heap.h"
#include <iostream>
#include <algorithm>
using namespace std;
CHeap::CHeap(int p[],int n):m_heapSize(n)
{
m_pIntArr = new int[m_heapSize];
for (int i =0; i<m_heapSize; i++)
{
m_pIntArr[i] = p[i];
}
}
CHeap::CHeap(const CHeap& heap):m_heapSize(heap.m_heapSize)
{
m_pIntArr = new int[m_heapSize];
for (int i =0; i<m_heapSize; i++)
{
m_pIntArr[i] = heap.m_pIntArr[i];
}
}
CHeap& CHeap::operator= (const CHeap& heap)
{
if (this != &heap)
{
m_heapSize = heap.m_heapSize;
m_pIntArr = new int[m_heapSize];
for (int i =0; i<m_heapSize; i++)
{
m_pIntArr[i] = heap.m_pIntArr[i];
}
}
return *this;
}
CHeap::~CHeap(void)
{
delete []m_pIntArr;
}
void CHeap::Max_Heaprity(int index,const int size)
{
int l,r,largest;
largest = index;
l = 2*index;
r = 2*index+1;
if (l<size&&m_pIntArr[l]>m_pIntArr[index])
{
largest = l;
}
if (r<size&&m_pIntArr[r]>m_pIntArr[largest])
{
largest = r;
}
if (largest != index)
{
swap(m_pIntArr[largest],m_pIntArr[index]);
Max_Heaprity(largest,size);
}
}
void CHeap::Build_MaxHeap()
{
for (int i = m_heapSize/2; i>=0 ; i--)
{
Max_Heaprity(i,m_heapSize);
}
}
void CHeap::HeapSort()
{
Build_MaxHeap();
//Output();
int size = m_heapSize;
for (int i = m_heapSize-1; i>=0; i--)
{
swap(m_pIntArr[i],m_pIntArr[0]);
size = size -1;
Max_Heaprity(0,size);
// /Output();
}
}
void CHeap::Output()
{
for (int i =0; i<m_heapSize ;i++)
{
cout<<m_pIntArr[i]<<" ";
}
cout<<endl;
}
今天CSDN的博客有点问题,不能上传代码!