堆排序

今天看了第六章的堆排序,故将其用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的博客有点问题,不能上传代码!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值