堆排序算法运行结果不正确。求助
今天看算法导论的时候,将堆排序实现,但是结果总是不正确。谁能帮忙解决一下?#ifndef HEAPSORT_H_
#define HEAPSORT_H_
#include <iostream>
#include <iomanip>
using std::cout;
using std::cerr;
using std::endl;
using std::setw;
template <class Type>
class MaxHeap
{
public:
MaxHeap(int sz);
MaxHeap(Type arr[],int n);
~MaxHeap();
int GetParentIndex(int i); //返回a[i]的父节点的下标
int GetLeftIndex(int i); //返回a[i]的左孩子的下标
int GetRightIndex(int i); //返回a[i]的右孩子的下标
void Max_HeapIFY(int i); //使以i为根的子树成为最大堆
void Exchange(int i,int j); //交换数组中的元素
void Buile_Heap(); //建堆
void HeapSort(); //运用堆排序算法
void PrintArayy(); //输出排序后的数组
private:
Type *array;
int length;
int heap_size;
};
template <class Type>
MaxHeap<Type>::MaxHeap(int sz)
{
if(sz<=0)
{
cerr<<"堆的大小不能小于1"<<endl;
exit(EXIT_FAILURE);
}
else
{
length=sz;
heap_size=sz;
array=new Type[sz];
}
}
template <class Type>
MaxHeap<Type>::MaxHeap(Type arr[],int n)
{
if(n<=0)
{
cerr<<"堆的大小不能小于1"<<endl;
exit(EXIT_FAILURE);
}
else
{
length=n;
heap_size=n;
array=new Type[n];
for(int i=0;i<n;i++)
{
array[i]=arr[i];
}
}
}
template <class Type>
MaxHeap<Type>::~MaxHeap()
{
delete []array;
}
template <class Type>
int MaxHeap<Type>::GetParentIndex(int i)
{
return i/2;
}
template <class Type>
int MaxHeap<Type>::GetLeftIndex(int i)
{
return 2*i+1;
}
template <class Type>
int MaxHeap<Type>::GetRightIndex(int i)
{
return 2*i+2;
}
template <class Type>
void MaxHeap<Type>::Exchange(int i,int j)
{
Type temp;
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
template <class Type>
void MaxHeap<Type>::Max_HeapIFY(int i)
{
int l=GetLeftIndex(i);
int r=GetRightIndex(i);
int largest;
if(l<heap_size&&array[l]>array[i])
largest=l;
else
largest=i;
if(r<heap_size&&array[r]>array[largest])
largest=r;
if(largest!=i)
{
Exchange(i,largest);
Max_HeapIFY(largest);
}
}
template <class Type>
void MaxHeap<Type>::Buile_Heap()
{
for(int i=0;i<length/2;i++)
{
Max_HeapIFY(i);
}
}
template <class Type>
void MaxHeap<Type>::HeapSort()
{
Buile_Heap();
for(int i=length-1;i>0;i--)
{
Exchange(0,i);
heap_size--;
Max_HeapIFY(0);
}
}
template <class Type>
void MaxHeap<Type>::PrintArayy()
{
for(int i=0;i<length;i++)
cout<<setw(5)<<array[i];
cout<<endl;
}
#endif
#include "heapsort.h"
#include <ctime>
#include <iomanip>
int main()
{
int a[10]={0};
srand(time(0));
for(int i=0;i<10;i++)
{
a[i]=rand()/1000+1;
}
MaxHeap<int> maxheap(a,sizeof(a)/sizeof(a[0]));
maxheap.HeapSort();
cout<<"排序后的结果是:"<<endl;
maxheap.PrintArayy();
return 0;
}
几乎每次运行结果都不对,感觉是在void Max_HeapIFY(int i)出错,很少把最大的元素调整到堆顶。求助求助