// heapSort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<cstdlib>
using namespace std;
void MaxHeapify(int *a,int i,int size); //保持最大堆特性
void BuildMaxHeap(int *a,int size) ; //建立最大堆
void HeapSort(int *a,int size); //堆排序
inline int Parent(int i); //算父节点
inline int Left(int i); //算左子节点
inline int Right(int i); //算右子节点
void Display(int *a,int size) ;
int _tmain(int argc, _TCHAR* argv[])
{
int size,*a;
while(1)
{
cout<<"输入字符串长度:"<<endl;
cin>>size;
if(size > 0) {
cout<<"请输入"<<size<<"个待排序数字:"<<endl;
a = (int*)malloc(size*sizeof(int));//a = new int [size];
for(int i=0; i<size; i++)
{
cin>>a[i];
}
HeapSort(a,size);
}
else
cout<<"输入长度错误!"<<endl;
Display(a,size);
}
return 0;
}
void MaxHeapify(int *a,int i,int size) //保持最大堆特性
{
int l,r,heapSize,largest,temp;
l = Left(i);
r = Right(i);
heapSize =size;
if (l<heapSize && a[l]>a[i] ) {
largest = l;
}
else largest = i;
if(r<heapSize && a[r]>a[largest]) {
largest = r;
}
if(largest != i) {
temp = a[i];
a[i] = a[largest];
a[largest] = temp;
MaxHeapify(a,largest,heapSize);
}
}
void BuildMaxHeap(int *a,int size)//建立最大堆
{
int heapSize = size;
int lengthArray =size;
for(int i=lengthArray-1; i>=0; i--)
{
MaxHeapify(a,i,heapSize);
}
}
void HeapSort(int *a,int size) //堆排序
{
int temp;
int lengthArray = size;
int heapSize = lengthArray;
BuildMaxHeap(a,heapSize);
for(int i=lengthArray-1; i>=1; i--)
{
temp = a[0];
a[0] = a[i];
a[i] = temp;
heapSize -= 1;
MaxHeapify(a,0,heapSize);
}
}
inline int Parent(int i)//计算父节点
{
i ++;
return i/2-1;
}
inline int Left(int i)//计算子左节点
{
i++;
return 2*i-1;
}
inline int Right(int i)//计算子右节点
{
i++;
return 2*i;
}
void Display(int *a,int size)//打印函数
{
for(int i=0; i<size; i++) //打印数组
{
cout<<a[i]<<" ";
}
cout<<endl<<endl;
}