堆形式:MAX-HEAPIFY
测试代码如下:
<pre name="code" class="cpp">/***********************************************************************************
程序名称 :heapsort_test
功能描述 : 堆排序,递归
修改历史 :
1.日 期 : 2015/10/5
作 者 : gqkly
内容 :
************************************************************************************/
#include <iostream>
#include <string>
#include <time.h>
#include <stdio.h>
using namespace std;
typedef int ElemType;
#define InitHeap(heap,len) { memset(&heap,0,sizeof(heap));heap.length=len;}
#define InitHeapA(heap) {heap.A=(ElemType*)malloc(heap.length*sizeof(ElemType));for(int i=0;i<heap.length;i++)heap.A[i]=rand()%50;}
#define Right_Of_I(i) (2*i+1)
#define Left_Of_I(i) (2*i)
#define swap1(a,b) {a=a+b;b=a-b;a=a-b;}
#define swap2(a,b) {a=a+b-(b=a);}
#define swap3(a,b) {b=a+(a=b)*0;}
#define swap4(a,b) {a=a^b;b=a^b;a=a^b;}
#define N 10
typedef struct HEAP_TYPE
{
ElemType *A;
int length;
}HEAP,*HEAP_PTR;
void Max_Heapify(HEAP* heap,int i);//中间层和第三层
void Build_Max_Heap(HEAP* heap);//中间层
void Heap_Sort(HEAP* heap);//第一层函数
void Print_Heap(HEAP heap,char *string);
int main()
{
HEAP heap_a;
InitHeap(heap_a,N);
InitHeapA(heap_a);
Print_Heap(heap_a,"start:");
Heap_Sort(&heap_a);
Print_Heap(heap_a,"MAX-HEAPIFY:");
getchar();
return 0;
}
void Max_Heapify(HEAP* heap,int i)//这个参数i为数学位置,函数内部转化为数组坐标
{
int largest;
int l=Left_Of_I(i);
int r=Right_Of_I(i);
if ( (l<=(*heap).length) && ((*heap).A[l-1])>((*heap).A[i-1]) )
{
largest=l;
}
else
largest=i;
if ( (r<=(*heap).length) && ((*heap).A[r-1])>((*heap).A[largest-1]) )
{
largest=r;
}
if (largest!=i)
{
swap1( (*heap).A[i-1],(*heap).A[largest-1] );
Max_Heapify(heap,largest);
}
}
void Build_Max_Heap(HEAP* heap)
{
int len=(*heap).length;
for (int i=(len/2);i>0;i--)
{
Max_Heapify(heap,i);
}
}
void Heap_Sort(HEAP* heap)
{
int tmp_size=(*heap).length;
Build_Max_Heap(heap);
for (int i=(*heap).length-1;i>0;i--)//长度的大小和坐标不一样
{
swap1((*heap).A[0],(*heap).A[i]);
(*heap).length--;//此处通过减小堆大小来为排序服务,所以需要在之后还原
Max_Heapify(heap,1);//1是数学位置--第一个元素
}
(*heap).length=tmp_size;//还原堆大小
}
void Print_Heap(HEAP heap,char *string)
{
int tmp=0;
int t=2;
cout<<"***********************************************"<<endl;
cout<<string<<endl;
for (int i=0;i<heap.length;i++)
{
tmp=i+1;
if ((i+1)==t)
{
t*=2;
tmp=i+1;
cout<<endl;
}
cout<<heap.A[i]<<' ';
}
cout<<endl;
}
运行: