堆排序的思想:
1.初始化创建堆,然后重复步骤2,3
2.交换堆顶和堆得最后一个元素,并缩小堆的大小
1.初始化创建堆,然后重复步骤2,3
2.交换堆顶和堆得最后一个元素,并缩小堆的大小
3.调整堆,即保证待排序的数组部分始终满足堆的结构
/*******************************************************/
/* this program is used to do a heap sort */
/* Author: SaoNian */
/* Time: 2012/11/11 */
/*******************************************************/
//#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <iomanip.h>
//using namespace std;
int * generateArray(int n);//generate an unsorted array with length n
void buildHeap(int *a,int n);//build a to be a heap
void max_heapify(int *a,int i,int length);//to Adjust the heap
void heapSort(int *a,int n);//heapSort
void showArray(int *a,int n);
int main()
{
int * arr=generateArray(30);
cout<<"the unsort Array:"<<endl;
showArray(arr,30);
heapSort(arr,30);
cout<<"now we Sort it:"<<endl;
showArray(arr,30);
return 0;
}
int * generateArray(int n)
{
int i;
int * arr=new int[n+1];
srand((int)time(NULL));
for(i=1;i<=n;i++)
{
arr[i]=rand()%n;
}
return arr;
}
void showArray(int *a,int n)
{
int i=1;
for(;i<=n;i++)
{
cout<<setw(4)<<a[i];
if(i%10==0)
{
cout<<endl;
}
}
}
void heapSort(int *a,int n)
{
buildHeap(a,n);
for(int i=n;i>=2;i--)
{
int tmp=a[1];
a[1]=a[i];
a[i]=tmp;
max_heapify(a,1,i-1);
}
}
void max_heapify(int *a,int i,int length)
{
int left=2*i;
int right=2*i+1;
int maxPos=i;
if(left<=length)
{
if(a[left]>=a[i])
{
maxPos=left;
}
}
if(right<=length)
{
if(a[right]>=a[maxPos])
{
maxPos=right;
}
}
if(maxPos!=i)
{
int tmp=a[maxPos];
a[maxPos]=a[i];
a[i]=tmp;
max_heapify(a,maxPos,length);
}
}
void buildHeap(int *a,int n)
{
int i=n/2;
for (;i>=1;i--)
{
max_heapify(a,i,n);
}
}
![](https://img-my.csdn.net/uploads/201211/11/1352620245_3857.jpg)