堆排序的时间复杂性为nlog(n),空间复杂度为o(1),为比较排序的下界,因此具有非常好的性能,使用堆,也很容易实现堆排序.
[code]
#include<iostream>
#include"MinHeap.h"
using namespace std;
template<class T>
void HeapSort(T a[],int n){
T temp;
MinHeap<T> *m_heap = new MinHeap<T>(a,n);
for(int i = n-1; i >= 1; i--){//a[0]与a[i]交换,重新调整堆0--->i-1
temp = a[i];
a[i] = a[0];
a[0] = temp;
m_heap->FilterDown(0,i-1);
}
}
void main(){
int a[5] = {3,2,1,4,5};
HeapSort(a,5);
for(int i = 0; i < 5; i++)
cout<<a[i]<<" ";
cout<<endl;
}
[/code]
[code]
#include<iostream>
#include"MinHeap.h"
using namespace std;
template<class T>
void HeapSort(T a[],int n){
T temp;
MinHeap<T> *m_heap = new MinHeap<T>(a,n);
for(int i = n-1; i >= 1; i--){//a[0]与a[i]交换,重新调整堆0--->i-1
temp = a[i];
a[i] = a[0];
a[0] = temp;
m_heap->FilterDown(0,i-1);
}
}
void main(){
int a[5] = {3,2,1,4,5};
HeapSort(a,5);
for(int i = 0; i < 5; i++)
cout<<a[i]<<" ";
cout<<endl;
}
[/code]