下载此文档

2016新编堆的遍历与堆排序.doc


文档分类:IT计算机 | 页数:约27页 举报非法文档有奖
1/27
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/27 下载此文档
文档列表 文档介绍
/*最大堆问题,堆数据结构是一颗完全二叉树,用数组来完成其物理实现,逻辑上实际是一种树形结构,
r是下标,parent(r)=int((r-1)/2);
leftchild(r)=2r+1;
rightchild(r)=2r+2;*/

template<class Elem>
class maxheap
{
private:
Elem* heapArray;
int maxsize;
int n;//堆的大小
public:
maxheap(int size = 10){
maxsize = size;
heapArray = new Elem[maxsize];//注意为中括号
n = 0;
}
~maxheap() {delete [] heapArray;}
int heapsize() {return n;}
int parent(int pos) {
return (pos-1)/2;
}
int leftchild(int pos) {
return 2*pos+1;
}
int rightchild(int pos) {
return 2*pos+2;
}
bool insert(Elem& e);
bool remove(int pos);
bool creatHeap(int ArrLen,Elem* arr);
void preorder(int pos);
void heapSort(int arrlen);
void print();
};
template<class Elem>
bool maxheap<Elem>::insert(Elem& e)
{
if(n>=maxsize-1)return false;
heapArray[n] = e;
// cout<<heapArray[n];
int temp = n;
Elem ha;
while(parent(temp)>=0 && heapArray[parent(temp)]<heapArray[temp]){
ha = heapArray[parent(temp)];
heapArray[parent(temp)] = heapArray[temp];
heapArray[temp] = ha;
// cout<<heapArray[temp]<<heapArray[parent(temp)];
temp = parent(temp);
}
n +=1;
return true;
}
template<class Elem>
bool maxheap<Elem>::creatHeap(int ArrLen, Elem* arr)
{
int n = ArrLen;
// heapArray = new Elem[ArrLen];
for(int i = 0; i<ArrLen-1 && arr[i]; i++){
insert(arr[i]);
}
return true;
}
template<class Elem>
bool maxheap<Elem>::remove(int pos)
{
if(pos<0 || pos>n)return false;
Elem temp;
temp = heapArray[pos];
heapArray[pos] = heapArray[n-1];
heapArray[n-1] = temp;
n = n-1;//删除一个节点后,堆节点数减1
int j = leftchild(pos);
while(j<=n-1){

if( heapArray[leftchild(pos)] < heapArray[rightchild(pos)] && rightchild(pos) <= n-1 ) j = rightchild(pos);//此时,j指向孩子中较大节点
if( heapArray[pos] >= heapArray[j] )break;//如果父节点比左右节点中较大节点大,则循环退出
temp = heapArray[j]; //父节点与较大节点交换
heapArray[j] = heapArray[pos];
heapArray[pos] = temp;
pos = j;
j = leftchild(pos);
}
return true;
}
templat

2016新编堆的遍历与堆排序 来自淘豆网www.taodocs.com转载请标明出处.

相关文档 更多>>
非法内容举报中心
文档信息
  • 页数27
  • 收藏数0 收藏
  • 顶次数0
  • 上传人cai.li.bin
  • 文件大小65 KB
  • 时间2018-11-12