#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *next; }N; void maxheap(N **,int n,int i); void display(N **head) { N *temp1=*head; while(temp1!=NULL) { printf("%d ",temp1->data); temp1=temp1->next; } } int main(int argc,char *argv[]) { N *head=NULL,*temp,*temp1; int a,l,r,n,i; n=0; FILE *fp; fp=fopen(argv[1],"r"); while((a=fscanf(fp,"%d",&l))!=EOF) { temp=(N*)malloc(sizeof(N)); temp->data=l; temp->next=NULL; if(head==NULL) head=temp; else { temp1=head; while(temp1->next!=NULL) temp1=temp1->next; temp1->next=temp; } n++; } display(&head); printf("\nAfter heapifying..\n"); for(i=(n/2)-1;i>=0;i--) maxheap(&head,n,i); temp1=head; while(temp1!=NULL) { printf("%d ",temp1->data); temp1=temp1->next; } printf("\n"); } void maxheap(N **head,int n,int i) { int larg,l,r,tem,lar; larg=i; l=(2*i)+1; r=(2*i)+2; lar=larg; N *temp=*head; while(lar!=0 && lar<n) { temp=temp->next; lar--; } N *temp1=*head; lar=l; while(lar!=0 && lar<=n) { temp1=temp1->next; lar--; } if(l<n && temp->data<temp1->data) { larg=l; lar=l; temp=*head; while(lar!=0 && lar<n) { temp=temp->next; lar--; } } lar=r; temp1=*head; while(lar!=0 && lar<n) { temp1=temp1->next; lar--; } if(r<n && temp->data<temp1->data) { larg=r; lar=r; temp=*head; while(lar!=0 && lar<=n) { temp=temp->next; lar--; } if(larg!=i) { tem=temp->data; temp->data=temp1->data; temp1->data=tem; maxheap(&(*head),n,larg); } }
// only heapify function
source share