-
Notifications
You must be signed in to change notification settings - Fork 15
/
Heap Sort.cpp
80 lines (67 loc) · 1.22 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
#include <iostream>
using namespace std;
int size = 0;
int parent(int i) { return ( (i-1)/2); }
int left(int i){ return (2 * i + 1); }
int right(int i){ return (2 * i + 2); }
void heapify(int heap[], int n, int i){
int l = left(i), r = right(i), s = i;
if( l < n && heap[l] < heap[s] ){
s = l;
}
if( r < n && heap[r] < heap[s] ){
s = r;
}
if( s != i ) {
swap(heap[s],heap[i]);
heapify(heap,n,s);
}
}
void build_heap(int heap[], int n){
for(int j = (n-1)/2; j >= 0; j--){
heapify(heap,n,j);
}
}
void heapSort(int heap[], int n){
build_heap(heap, n);
for (int i = n-1; i > 0; i--)
{
swap(heap[0],heap[i]);
heapify(heap,i,0);
}
}
int extractMin(int heap[]){
int root = heap[0];
heap[0] = heap[size-1];
size -= 1;
return root;
}
void decreaseKey(int heap[], int i,int val){
heap[i] = val;
while(i != 0 && heap[parent(i)] > heap[i] ){
swap(heap[parent(i)], heap[i]);
i = parent(i);
}
}
int main()
{
int t; cin >> t;
while(t--){
int n; cin >> n;
int a[n];
size = 0;
for (int i = 0; i < n; i++)
{
cin >> a[i];
size++;
}
build_heap(a,n);
cout << extractMin(a) << '\t';
//decreaseKey(heap,
for (int i = 0; i < size ; i++)
{
cout<<a[i]<<"\t";
}
cout << endl;
}
}