-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.cpp
93 lines (83 loc) · 1.48 KB
/
heap.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
89
90
91
92
93
/*************************************************************************
> File Name: 2.cpp
> Author: Louis1992
> Mail: zhenchaogan@gmail.com
> Blog: http://gzc.github.io
> Created Time: 一 12/22 21:47:37 2014
************************************************************************/
#include<iostream>
using namespace std;
/*
* get the parent of this node
*/
int parent(int i)
{
return (i-1)/2;
}
/*
* get the left child
*/
int left(int i)
{
return 2*i+1;
}
/*
* get the right child
*/
int right(int i)
{
return 2*i+2;
}
/*
* construct a sub-tree whose root is node i
*/
void maxHeapify(int A[], int n, int i)
{
int l = left(i);
int r = right(i);
int largest(0);
if (l <= (n-1) && A[l] > A[i])
largest = l;
else
largest = i;
if (r <= (n-1) && A[r] > A[largest])
largest = r;
if(largest != i)
{
swap(A[i], A[largest]);
maxHeapify(A, n, largest);
}
}
/*
* build the heap
*/
void buildMaxHeap(int A[], int n)
{
for(int i = n/2-1;i >= 0;i--)
maxHeapify(A, n, i);
}
/*
* heapsort
*/
void heapsort(int A[], int n)
{
buildMaxHeap(A, n);
for(int i = n-1;i > 0;i--)
{
swap(A[0],A[i]);
maxHeapify(A, --n, 0);
}
}
void print(int A[], int n)
{
for(int i = 0;i < n;i++)
cout << A[i] << " ";
cout << endl;
}
int main()
{
int A[10] = {16,14,10,8,7,9,3,2,4,1};
heapsort(A, 10);
print(A, 10);
return 0;
}