// heapBuild.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <malloc.h>
int array[] = { 150,80,40,30,10,70,110,100,20,90,60,50,120,140,130};
typedef struct Heap{
int Capacity;
int Size;
int *Elements;
}Heap;
Heap* Initialize(int max)
{
Heap * H;
H = (Heap *)malloc(sizeof(Heap));
H->Elements = (int *)malloc(sizeof(int)*(max+1));
H->Capacity = max;
H->Size = 0;
H->Elements[0] = 0;
return H;
}
int putHeap(Heap *H,int array[], int num)
{
for(int i =0;i< num;i++)
H->Elements[i+1] = array[i];
H->Size = num;
return 0;
}
int printHeap(Heap *H)
{
for(int i = 1;i <= H->Size;i++)
printf(" %d",H->Elements[i]);
printf("\n");
return 0;
}
int deletemin(Heap *H)
{
int i;
int min,last,child;
min = H->Elements[1];
last = H->Elements[H->Size--];
for(i =1;i*2<H->Size;i=child)
{
child = 2*i;
if(child!=H->Size && H->Elements[child+1]<H->Elements[child])
child++;
if(last >H->Elements[child])
H->Elements[i] = H->Elements[child];
else
break;
}
H->Elements[i] =last;
return min;
}
int PrecolateDown(Heap *H,int location)
{
int i = location,child;
int temp = H->Elements[location];
for(;i*2< H->Size; i=child)
{
child = 2*i;
if(child != H->Size&&H->Elements[child+1]<H->Elements[child])
child++;
if(temp >H->Elements[child])
H->Elements[i] = H->Elements[child];
else
break;
}
H->Elements[i] = temp;
return 0;
}
int BuildHeap(Heap *H)
{
for(int i = H->Size/2;i>0;i--)
{
PrecolateDown(H,i);
printHeap(H);
}
return 0;
}
int main(int argc, char* argv[])
{
Heap *H = Initialize(20);
putHeap(H,array,sizeof(array)/sizeof(int));
printHeap(H);
printf("build heap\n\n");
//构建堆
BuildHeap(H);
printf("heap sort result\n\n");
//进行堆排序
while(H->Size)
{
printf(" %d",deletemin(H));
}
return 0;
}