Files
DataStruct/include/HeapSort.h
2024-06-30 22:03:12 +08:00

122 lines
2.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 版权所有 (c) ling 保留所有权利。
// 除非另行说明否则仅允许在DataStruct中使用此文件中的代码。
//
// 由 ling 创建于 24-6-30.
//
#ifndef DATASTRUCT_HEAPSORT_H_19
#define DATASTRUCT_HEAPSORT_H_19
#include <vector>
namespace ling {
/**
* 堆排序
*/
template<typename T>
class HeapSort {
private:
std::vector<T> *list;
protected:
virtual bool isBig(const T &, const T &) const = 0;
[[nodiscard]] inline bool isLeft(int i) const {
return left(i) < list->size();
}
[[nodiscard]] inline bool isRight(int i) const {
return right(i) < list->size();
}
[[nodiscard]] inline int parent(int i) {
return (i - 1) / 2;
}
[[nodiscard]] inline int left(int i) const {
return i * 2 + 1;
}
[[nodiscard]] inline int right(int i) const {
return i * 2 + 2;
}
/// 上滤
void top(int i) {
while (i > 0 && isBig((*list)[i], (*list)[parent(i)])) {
std::swap((*list)[i], (*list)[parent(i)]);
i = parent(i);
}
}
/// 下滤
void bottom(int i, int size) {
while (true) {
int largest = i;
int l = left(i);
int r = right(i);
if (l < size && isBig((*list)[l], (*list)[largest])) {
largest = l;
}
if (r < size && isBig((*list)[r], (*list)[largest])) {
largest = r;
}
if (largest != i) {
std::swap((*list)[i], (*list)[largest]);
i = largest;
} else {
break;
}
}
}
void bottom(int i) {
int size = list->size();
bottom(i, size);
}
public:
explicit HeapSort(std::vector<T> &list) {
this->list = &list;
if (this->list->size() <= 1)
return;
}
void init() {
for (int i = parent(list->size() - 1); i >= 0; i--) {
bottom(i);
}
}
void insert(T val) {
list->push_back(std::move(val));
top(list->size() - 1);
}
void sort() {
int n = list->size();
for (int i = n - 1; i > 0; i--) {
std::swap((*list)[0], (*list)[i]);
bottom(0, i);
}
}
};
template<typename T>
class HeapSortDefault : public HeapSort<T> {
protected:
bool isBig(const T &t, const T &t1) const override {
return t > t1;
}
public:
explicit HeapSortDefault(std::vector<T> &list) : HeapSort<T>(list) {
}
};
} // ling
#endif //DATASTRUCT_HEAPSORT_H_19