-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.hpp
More file actions
53 lines (47 loc) · 1.14 KB
/
HeapSort.hpp
File metadata and controls
53 lines (47 loc) · 1.14 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
48
49
50
51
52
53
#ifndef HEAPSORT_H
#define HEAPSORT_H
#include <iostream>
template<class T>
class HeapSort {
public:
HeapSort(){} ;
void sort(T* arr, int size);
private:
void fixDown(T* array, int k, int n);
void heapify(T* array, int n);
};
template<class T>
void HeapSort<T>::heapify(T* array, int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
fixDown(array, i, n);
}
}
template<class T>
void HeapSort<T>::sort(T* arr, int size) {
heapify(arr, size);
for (int i = 0; i < size - 1; i++) {
T temp = arr[size - 1 - i];
arr[size - 1 - i] = arr[0];
arr[0] = temp;
// std::swap(arr[size-1-i], arr[0]);
fixDown(arr, 0, size-1-i);
}
}
template<class T>
void HeapSort<T>::fixDown(T* array, int k, int n) {
T temp;
while(k<n/2){
int child = 2*k+1;
if(child+1<n && array[child]<array[child+1]){
child++;
}
if(array[k]>=array[child]){
break;
}
temp = array[k];
array[k] = array[child];
array[child] = temp;
k = child;
}
}
#endif