//implements standard heap functions
//heap.c@standard c library(*SCL*) by ASHISH TIWARI
/*
You may print, store code from this program for your personal,
noncommercial use. By accessing this code, you agree not to reproduce,
distribute,
display or transmit information from this code in any form or by any means
without
the permission of ASHISH TIWARI, with this exception: You may occasionally
reproduce,
distribute, display or transmit an insubstantial portion of the information, for
a
noncommercial purpose, to a limited number of individuals. ASHISH TIWARI does
not warrant
the accuracy, completeness, timeliness, merchantability or fitness for a
particular purpose
of the cose,though every care has been taken in making this code and has been
compiled
on standard gcc compiler provided by GNU. ASHISH TIWARI shall not be liable for
any
errors or omissions in the information or decisions made or actions taken in
reliance
on the code.
"*SCL*" is a registered trademark of ASHISH TIWARI, IITKGP.
All contents of "*SCL*" is copyright ©2000-.... ,ASHISH TIWARI, IITKGP
unless otherwise noted. Reproduction in part or in whole without
permission is expressly prohibited.
*/
#include<stdio.h>
#define l 2*i
#define r 2*i+1
#define num 11
void buildheap(int arr[],int size);
void heapify(int arr[],int size,int i);
void swap(int arr[],int p,int q);
void heapsort(int arrheap[],int size);
int extractmin(int arr[],int *size);
main()
{
int i,size=num;
int arr[num];
int arrheap[num];
for(i=1;i<num;i++)
scanf("%d",&arr[i]);
buildheap(arr,size);
for(i=1;i<num;i++)
arrheap[i]=arr[i];
heapsort(arrheap,size);
printf("sorted list=>");
for(i=1;i<num;i++)
printf("%d ",arrheap[i]);
printf("\nextractminlist=>");
for(i=1;i<num;i++)
printf("%d->",extractmin(arr,&size));
}
void buildheap(int arr[],int size)
{
int i;
for(i=(size)/2;i>=1;i--)
{
heapify(arr,size,i);
}
printf("heap=>");
for(i=1;i<num;i++)
{
printf("%d->",arr[i]);
}
printf("\n");
}
void heapify(int arr[],int size,int i)
{
int smallest;
if(arr[i]>arr[l] && l<=size-1)
smallest=l;
else
smallest=i;
if(arr[smallest]>arr[r] && r<=size-1)
smallest=r;
if(i!=smallest)
{
swap(arr,i,smallest);
heapify(arr,size,smallest);
}
}
void swap(int arr[],int p,int q)
{
int temp;
temp=arr[q];
arr[q]=arr[p];
arr[p]=temp;
}
void heapsort(int arrheap[],int size)
{
int i;
for(i=size-1;i>=2;i--)
{
swap(arrheap,1,i);
size--;
heapify(arrheap,size,1);
}
}
int extractmin(int arr[],int *size)
{
int min;
if(*size-1<1)
{
printf("heap has no more elements\n");
exit(1);
}
else
{
min=arr[1];
arr[1]=arr[*size-1];
(*size)--;
heapify(arr,*size,1);
}
return(min);
}