Created
April 24, 2010 17:34
-
-
Save justjkk/377800 to your computer and use it in GitHub Desktop.
Implementing Heap Sort in C language
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Implementing Heap Sort in C language | |
#include<stdio.h> | |
void heap(int *a, int n); | |
void create_heap(int *a, int n); | |
void main() | |
{ | |
int a[50],i,n; | |
printf("Enter the limits: "); | |
scanf("%d",&n); | |
printf("Enter the elements: "); | |
for(i=0;i<n;i++) | |
scanf("%d",&a[i]); | |
heap(a,n); | |
printf("The sorted list is...\n"); | |
for(i=0;i<n;i++) | |
printf("%d\n",a[i]); | |
} | |
void create_heap(int *a, int n) | |
{ | |
int i,j,q,key; | |
for(q=1;q<n;q++) | |
{ | |
i=q; | |
key=a[q]; | |
j=(int)(i/2); //Emphasizing the need for integer division | |
while((i>0)&&(key>a[j])) | |
{ | |
a[i]=a[j]; | |
i=j; | |
j=(int)(i/2); | |
if(j<0) | |
j=0; | |
} | |
a[i]=key; | |
} | |
} | |
void heap(int *a, int n) | |
{ | |
int i,j,q,key,temp; | |
create_heap(a,n); | |
for(q=n-1;q>=1;q--) | |
{ | |
temp=a[0]; | |
a[0]=a[q]; | |
a[q]=temp; | |
i=0; | |
key=a[0]; | |
j=1; | |
if((j+1)<q) | |
if(a[j+1]>a[j]) | |
j++; | |
while((j<=(q-1))&&(a[j]>key)) | |
{ | |
a[i]=a[j]; | |
i=j; | |
j=2*i; | |
if((j+1)<q) | |
if(a[j+1]>a[j]) | |
j++; | |
else if(j>n-1) | |
j=n-1; | |
a[i]=key; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment