heapsort的实现

#pragma once
#include <iostream>
using namespace std;

template <class Type>
class HeapList
{
 private:
  Type* entry;
  int count;
 public:
  
  HeapList();
  HeapList(int n);
  HeapList(Type arr[],int n);
  ~HeapList(){
   if(count > 0)
    delete []entry;
  };
  void buildHeap();
  void adjustHeap(const Type &current,int low, int high);
  void heapSort();
  //friend ostream& operator<<(ostream &os, const HeapList<Type> &hlist);
  void printAll();
};

template <class Type>
HeapList<Type>::HeapList()
{
 count = 0;
 entry = NULL;
}

template <class Type>
HeapList<Type>::HeapList(int n)
{
 count = n;
 entry = new Type[count];
 for(int i = 0; i < count; i++)
 {
  entry[i] = 0; //是否需要给初值?潜在bug。与Type实例有关
 }
}

template <class Type>
HeapList<Type>::HeapList(Type arr[], int n)
{
 count = n;
 entry = new Type[count];
 for(int i = 0; i < count; i++)
 {
  entry[i] = arr[i];
 }
}

template <class Type>
void HeapList<Type>::adjustHeap(const Type &current, int low, int high)
{
 int large;//保存较大孩子的位置
 large = low*2+1; //成为low的左孩子
 while(large <= high)
 {
  if(large < high && entry[large] < entry[large+1])
   large++;
  if(current >= entry[large])//又一潜在bug,是否重载〉=
   break;
  else
  {
   entry[low] = entry[large];
   low = large;//降为左或右子树
   large = low*2+1;
  }
 }
 entry[low] = current;//把最初需要调整的数字放在正确的位置
}
//建堆算法:所有叶子节点都符合堆的定义,故从第一个非叶子节点开始
//用上述算法把该子树调整为堆,直至整个完全二叉树调整成为初始堆
template <class Type>
void HeapList<Type>::buildHeap()
{
 int low;
 for(low = count/2-1; low >= 0; low--)
 {
  Type current = entry[low];
  adjustHeap(current, low, count-1);
 }
}

template <class Type>
void HeapList<Type>::heapSort()
{
 Type current;
 int last_unsorted;
 buildHeap();
 for(last_unsorted = count -1; last_unsorted > 0; last_unsorted--)
 {
  current = entry[last_unsorted];
  entry[last_unsorted] = entry[0];
  adjustHeap(current, 0, last_unsorted-1);
 }
}

template <class Type>
void HeapList<Type>::printAll()
{
 for(int i = 0; i < count; i++)
  cout<<entry[i]<<endl;
}
/*template <class Type>
ostream& operator << (ostream &os, const HeapList<Type> &hlist)
{
 for(int i = 0; i < hlist.count; i++)
  os<<hlist.entry[i]<<endl;
 return os;
}*/

//cpp

#include "heaph.h"


int main()
{
 int arr[5] = {5,1,3,4,2};
 HeapList<int>* hlist = new HeapList<int>(arr, 5);
 hlist->heapSort();
 //for(int i = 0; i < 5; i++)
 // cout << hlist->entry[i] << endl;

 //cout << *hlist;
 hlist->printAll();
 delete hlist;
 return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值