-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathheapSort.c
74 lines (72 loc) · 1.13 KB
/
heapSort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<stdio.h>
#include<stdlib.h>
void heapify(int *,int ,int );
void buildMinHeap(int *,int);
void heapSort(int *,int );
int main()
{
int i,j,n,*heap;
scanf("%d",&n);
heap=(int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",heap+i);
buildMinHeap(heap,n);
for(i=0;i<n;i++)
printf("%d ",heap[i]);
printf("\n");
heapSort(heap,n);
for(i=0;i<n;i++)
printf("%d ",heap[i]);
return 0;
}
void buildMinHeap(int *h,int n)
{ //building heap structure
//shiftdown O(n)
//more efficient
//lesser no of swapping required
int i;
for(i=n-1;i>=0;i--)
heapify(h,i,n);
}
void heapify(int *heap,int ind,int n)
{
int tmp,k;
while(ind<n)
{
if(ind*2+1>=n)
break;
else if(ind*2+2>=n)
k=ind*2+1;
else
{
//min among the children
if(heap[ind*2+1]>heap[ind*2+2])
k=ind*2+2;
else
k=ind*2+1;
}
if(heap[ind]>heap[k])
{
tmp=heap[ind];
heap[ind]=heap[k];
heap[k]=tmp;
ind=k;
}
else
break;
}
}
void heapSort(int *heap,int n )
{
int i,j;
i=n-1;
while(i>=0)
{
//swap 0th with ith element
j=heap[0];
heap[0]=heap[i];
heap[i]=j;
i--;//shrinking unsorted area
heapify(heap,0,i);
}
}