Altered
This commit is contained in:
110
BinaryTree/priorityQueue/maxHeap/maxHeap.h
Normal file
110
BinaryTree/priorityQueue/maxHeap/maxHeap.h
Normal file
@@ -0,0 +1,110 @@
|
||||
//
|
||||
// Created by PC on 25-8-9.
|
||||
//
|
||||
|
||||
#ifndef MAXHEAP_H
|
||||
#define MAXHEAP_H
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <bits/ostream.tcc>
|
||||
|
||||
template<class T>
|
||||
class maxHeap {
|
||||
private:
|
||||
std::vector<T> data;
|
||||
int dsize;
|
||||
public:
|
||||
maxHeap() : dsize(0) {}
|
||||
~maxHeap() = default;
|
||||
|
||||
bool empty() const;
|
||||
int size() const;
|
||||
void pop();
|
||||
void push(const T& x);
|
||||
T& top();
|
||||
void display();
|
||||
};
|
||||
|
||||
template<class T>
|
||||
bool maxHeap<T>::empty() const {
|
||||
return data.size() == 0;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
int maxHeap<T>::size() const {
|
||||
return dsize;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void maxHeap<T>::pop() {
|
||||
if (data.empty()) {
|
||||
std::cerr << "Empty Heap!" << std::endl;
|
||||
return;
|
||||
}
|
||||
data.at(0) = data.at(data.size() - 1);
|
||||
dsize--;
|
||||
data.pop_back();
|
||||
//正确的下沉逻辑:(记住如下写法,短小精悍
|
||||
//先找左节点(如果有)再找右节点(如果有)比较左右节点,选择更大的那个作为可能交换的目标
|
||||
//如果当前节点已经比这个目标大 → 停 ;否则 → 交换并继续下沉
|
||||
int index = 0;
|
||||
int left = 2 * index + 1;
|
||||
int right = 2 * index + 2;
|
||||
while (left < data.size()) {
|
||||
int largest = index;
|
||||
if (data[left] > data[largest]) largest = left;
|
||||
if (data[right] > data[largest]) largest = right;
|
||||
if (largest == index) break;
|
||||
|
||||
std::swap(data[index], data[largest]);
|
||||
index = largest;
|
||||
left = 2 * index + 1;
|
||||
right = 2 * index + 2;
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void maxHeap<T>::push(const T &x) {
|
||||
data.push_back(x); // 新元素放到末尾
|
||||
dsize++;
|
||||
|
||||
int idx = dsize - 1; // 当前节点下标
|
||||
while (idx > 0) {
|
||||
int parent = (idx - 1) / 2;
|
||||
if (data[idx] > data[parent]) { // 如果比父节点大,就交换
|
||||
std::swap(data[idx], data[parent]);
|
||||
idx = parent; // 继续向上
|
||||
} else {
|
||||
break; // 满足堆性质,结束
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
template<class T>
|
||||
T & maxHeap<T>::top() {
|
||||
if (data.empty()) {
|
||||
std::cerr << "Empty Heap" << std::endl;
|
||||
}
|
||||
else {
|
||||
return data[0];
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void maxHeap<T>::display() {
|
||||
int jmp = 1;
|
||||
int cnt = jmp;
|
||||
for (int i = 0; i < data.size(); ++i) {
|
||||
std::cout << data.at(i) << " ";
|
||||
cnt--;
|
||||
if (cnt == 0) {
|
||||
jmp *= 2;
|
||||
cnt = jmp;
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
std::cout << std::endl << std::endl;
|
||||
}
|
||||
|
||||
#endif //MAXHEAP_H
|
Reference in New Issue
Block a user