forked from leo000leo/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.h
More file actions
47 lines (41 loc) · 1.19 KB
/
Copy pathheap_sort.h
File metadata and controls
47 lines (41 loc) · 1.19 KB
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
//
// heap_sort
// Algorithm
//
// Created by dtysky on 16/10/28.
// Copyright © 2016 [email protected]. All rights reserved.
//
#ifndef ALGORITHM_HEAP_SORT_H
#define ALGORITHM_HEAP_SORT_H
#include <cstdio>
#include <vector>
#include "binary_heap.h"
namespace my_algorithm {
// time: O(nlog(n))
// space: O(n)
template<typename T, size_t Size>
void heapSort(std::vector<T>& t_vector, bool reverse = false) {
auto size = size_t(t_vector.size());
if (size > Size) {
throw std::out_of_range("Vector's size must be less than heap's.");
}
if (reverse) {
data_structures::MaxBinaryHeap<T, Size> heap;
for (int i = 0; i < size; i++) {
heap.insert(t_vector[i]);
}
for (int i = 0; i < size; i++) {
t_vector[i] = heap.deleteTop();
}
} else {
data_structures::MinBinaryHeap<T, Size> heap;
for (int i = 0; i < size; i++) {
heap.insert(t_vector[i]);
}
for (int i = 0; i < size; i++) {
t_vector[i] = heap.deleteTop();
}
}
}
}
#endif //ALGORITHM_HEAP_SORT_H