#include"head.h"
static int left(int i)
{
return (i<<1);
}
static int right(int i)
{
return ((i<<1)+1);
}
static int parent(int i)
{
return (i/2);
}
void swap(ElementType *x,ElementType *y)
{
ElementType tmp;
tmp=*x;
*x=*y;
*y=tmp;
}
void maxHeapIfy(ElementType a[],int i,int n)
{
int l,r,largest;
l=left(i);
r=right(i);
if(l<=n && a[l]>a[i])
largest=l;
else
largest=i;
if(r<=n && a[r]>a[largest])
largest=r;
if(largest!=i)
{
swap(&a[largest],&a[i]);
maxHeapIfy(a,largest,n);
}
}
void buildMaxHeap(ElementType a[],int n)
{
int i;
for(i=n/2;i>=1;i--)
maxHeapIfy(a,i,n);
}
void heapSort(ElementType a[],int n)
{
int i;
buildMaxHeap(a,n);
for(i=n;i>1;i--)
{
swap(&a[1],&a[i]);
maxHeapIfy(a,1,i-1);
}
}
ElementType heapMaximum(ElementType a[])
{
return a[1];
}
ElementType heapExtractMax(ElementType a[],int *heapSize)
{
ElementType max;
if(*heapSize<1)
return 0;
max=a[1];
a[1]=a[*heapSize-1];
--*heapSize;
maxHeapIfy(a,1,*heapSize);
return max;
}
void heapIncreaseKey(ElementType a[],int i,ElementType key)
{
if(key<a[i])
exit(1);
a[i]=key;
while(i>1 && a[parent(i)]<a[i])
{
swap(&a[i],&a[parent(i)]);
i=parent(i);
}
}
void maxHeapInsert(ElementType a[],ElementType key,int *heapSize)
{
a[*heapSize]=INF;
heapIncreaseKey(a,*heapSize,key);
}
void heapDelete(ElementType a[],int i,int *heapSize)
{
ElementType key;
a[i]=a[*heapSize-1];
--(*heapSize);
key=a[i];
if(key<=a[parent(i)])
maxHeapIfy(a,i,*heapSize);
else
{
while(i>1 && a[parent(i)]<a[i])
{
swap(&a[i],&a[parent(i)]);
i=parent(i);
}
}
}
#define INF -10000
#define MAX 11
#define MAXLENTH 10
typedef int ElementType;
void buildMaxHeap(ElementType a[],int n);
void heapSort(ElementType a[],int n);
void heapDelete(ElementType a[],int i,int *heapSize);
void maxHeapInsert(ElementType a[],ElementType key,int *heapSize);
void heapIncreaseKey(ElementType a[],int i,ElementType key);
ElementType heapExtractMax(ElementType a[],int *heapSize);
ElementType heapMaximum(ElementType a[]);
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"head.h"
int main()
{
int i,h,*heapSize;
ElementType a[MAX],max;
h=MAXLENTH;
heapSize=&h;
srand((unsigned)time(NULL));
for(i=1;i<*heapSize;i++)
a[i]=rand()%10+1;
buildMaxHeap(a,*heapSize);
//maxHeapInsert(a,0,heapSize);
//b=heapMaximum(a);
//printf("%d\n",b);
//(heapIncreaseKey(a,8,15));
max=heapExtractMax(a,heapSize);
printf("%d\n",max);
//heapSort(a,MAX);
for(i=1;i<*heapSize;i++)
{
printf("%d\t",a[i]);
if(i%10==0)
printf("\n");
}
return 0;
}