标签:
#ifndef HEAP_SORT_H
#define HEAP_SORT_H
#include<iostream>
#include<string>
template<class Type>
class HeapSort{
private:
Type *ptr;
int Length;
int HeapSize;
public:
int rightHeap(int i){
return 2*i+1;
}
int leftHeap(int i){
return 2*i+2;
}
HeapSort(Type *p,int Len){
this->ptr=p;
this->Length=Len;
this->HeapSize=Len;
}
void maxHeapy(int idx){
int right=rightHeap(idx);
int left=leftHeap(idx);
int maxIdx=idx;
if(right<HeapSize&&ptr[right]>ptr[idx]){
maxIdx=right;
}
if(left<HeapSize&&ptr[left]>ptr[maxIdx]){
maxIdx=left;
}
if(maxIdx!=idx){
Type temp=ptr[idx];
ptr[idx]=ptr[maxIdx];
ptr[maxIdx]=temp;
maxHeapy(maxIdx);
}
}
void buildMaxHeapy(){
for(int i=HeapSize/2+2; i>=0;i--){
maxHeapy(i);
}
}
void heapSort(){
for(int i=Length-1;i>0;i--){
buildMaxHeapy(); //建立堆
Type temp=ptr[i];
ptr[i]=ptr[0];
ptr[0]=temp;
--HeapSize;
}
}
};
#endif
int rightHeap(int i){
return 2*i+1;
}
int leftHeap(int i){
return 2*i+2;
}
void maxHeapy(int idx){
int right=rightHeap(idx);
int left=leftHeap(idx);
int maxIdx=idx;
if(right<HeapSize&&ptr[right]>ptr[idx]){
maxIdx=right;
}
if(left<HeapSize&&ptr[left]>ptr[maxIdx]){
maxIdx=left;
}
if(maxIdx!=idx){
Type temp=ptr[idx];
ptr[idx]=ptr[maxIdx];
ptr[maxIdx]=temp;
maxHeapy(maxIdx);
}
}
if(right<HeapSize&&ptr[right]>ptr[idx]){
maxIdx=right;
}
if(left<HeapSize&&ptr[left]>ptr[maxIdx]){
maxIdx=left;
}
if(right<HeapSize&&ptr[right]>ptr[idx]){
maxIdx=right;
}
if(left<HeapSize&&ptr[left]>ptr[idx]){
maxIdx=left;
}
if(maxIdx!=idx){
Type temp=ptr[idx];
ptr[idx]=ptr[maxIdx];
ptr[maxIdx]=temp;
maxHeapy(maxIdx);
}
if(right<HeapSize&&ptr[right]>ptr[idx]){
maxIdx=right;
}
if(left<HeapSize&&ptr[left]>ptr[maxIdx]){
maxIdx=left;
}
void buildMaxHeapy(){
for(int i=HeapSize/2; i>=0;i--){
maxHeapy(i);
}
}
void heapSort(){
for(int i=Length-1;i>0;i--){
buildMaxHeapy(); //建立堆
Type temp=ptr[i];
ptr[i]=ptr[0];
ptr[0]=temp;
--HeapSize;
}
标签:
原文地址:http://www.cnblogs.com/yml435/p/4655561.html