forked from Mugdha-Hazra/PrepBytes-questions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHeap Sort.cpp
88 lines (84 loc) · 1.31 KB
/
Heap Sort.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
int parent(int i)
{
return i/2;
}
int left(int i)
{
return i*2;
}
int right(int i)
{
return (i*2)+1;
}
void swap(int *a,int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void insert(int heap[], int *size, int val)
{
int i = *size;
heap[i] = val;
(*size)++;
while( i!=1 && heap[parent(i)]<heap[i])
{
swap(&heap[parent(i)],&heap[i]);
i = parent(i);
}
}
void heapify(int heap[],int i, int size)
{
int l = left(i);
int r = right(i);
int s= i;
if(l<size && heap[l]< heap[i])
s = l;
if(r<size && heap[r]<heap[s])
s = r;
if(s!=i)
{
swap(&heap[i],&heap[s]);
heapify(heap,s,size);
}
}
void heapSort(int heap[], int n)
{
// build heap (rearrange array)
for (int i = n / 2 ; i >= 1; i--)
heapify(heap,i,n);
// one by one extract an element from heap
for (int i=n-1; i>=1; i--)
{
// move current root to end
swap(&heap[1], &heap[i]);
// call max heapify on the reduced heap
heapify(heap,1,i);
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int size=1;
int *heap = (int *)malloc(sizeof(int)*(n+1));
while(n--)
{
int a;
scanf("%d",&a);
insert(heap,&size,a);
}
heapSort(heap,size);
for(int i=1;i<size;i++)
{
printf("%d ",heap[i]);
}
printf("\n");
}
return 0;
}