Heap数组实现

来源:互联网 发布:立体画图软件 编辑:程序博客网 时间:2024/06/07 15:47

#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 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);
 BuildHeap(H);
 return 0;
}