-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap.cpp
58 lines (49 loc) · 840 Bytes
/
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
#include "Heap.h"
Heap::Heap(elemtype a[],int len,int size){
length = len;
heap_size = size;
for (int i = 1; i < len; ++i)
{
this->data[i] = a[i];
}
buildMaxHeap(size);
}
void Heap::maxHeapify(int s){
int l = LEFT(s);
int r = RIGHT(s);
elemtype temp;
int largest = s;
if (l <= heap_size && data[s] < data[l])
{
largest = l;
}
if (r <= heap_size && data[largest] < data[r])
{
largest = r;
}
if (largest != s)
{
temp = data[s];
data[s] = data[largest];
data[largest] = temp;
maxHeapify(largest);
}
}
void Heap::buildMaxHeap(int size){
heap_size = size;
for (int i = size/2; i >= 1; --i)
{
maxHeapify(i);
}
}
void Heap::heapSort(){
buildMaxHeap(length);
for (int i = length; i > 0; --i)
{
elemtype temp;
temp = data[1];
data[1] = data[i];
data[i] = temp;
maxHeapify(length-1);
}
}