-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapSort.cpp
49 lines (45 loc) · 1.3 KB
/
heapSort.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
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
void fixHeap(vector <int>& nonSortedVector, int startingNode, int size);
void createHeap(vector <int>& nonSortedVector);
void heapSort(vector <int>& nonSortedVector)
{
createHeap(nonSortedVector);
int size = nonSortedVector.size() - 1;
for (int i = nonSortedVector.size() - 1; i >= 1; i--)
{
int temp = nonSortedVector[size];
nonSortedVector[size] = nonSortedVector[0];
nonSortedVector[0] = temp;
size--;
fixHeap(nonSortedVector, 0, size);
}
}
void createHeap(vector <int>& nonSortedVector)
{
for (int i = (nonSortedVector.size() -1)/ 2; i >= 0; i--)
{
fixHeap(nonSortedVector, i,nonSortedVector.size());
}
}
void fixHeap(vector <int>& nonSortedVector, int startingNode, int size)
{
int left = startingNode * 2 + 1;
int right = startingNode * 2 + 2;
int max = -1;
if ((left < size) && (nonSortedVector[left] > nonSortedVector[startingNode]))
max = left;
else
max = startingNode;
if ((right < size) && (nonSortedVector[right] > nonSortedVector[max]))
max = right;
if (max != startingNode)
{
int temp = nonSortedVector[startingNode];
nonSortedVector[startingNode] = nonSortedVector[max];
nonSortedVector[max] = temp;
fixHeap(nonSortedVector, max, size);
}
}