1 Star 0 Fork 43

郑旭烜/lec07-heap

forked from SE-201/lec07-heap 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Heapmyanswer.java 2.73 KB
一键复制 编辑 原始数据 按行查看 历史
郑旭烜 提交于 2020-12-14 20:39 . 作业
public class Heapmyanswer<T extends Comparable<T>> {
public T[] heap;
public int SIZE;
public int count;
Heapmyanswer(int size) {
SIZE = size;
// reference: https://stackoverflow.com/questions/34827626/cannot-be-cast-to-ljava-lang-comparable
heap = (T[]) new Comparable[SIZE];
count = 0;
}
public class MaxHeap<T extends Comparable<T>> {
private int size;
private int count;
private T[] heap;
public MaxHeap(int size) {
heap = (T[]) new Comparable[size];
this.size = size;
count = 0;
}
// TODO: 完善add函数
public void add(T item) {
if (count == 0) {
heap[count] = item;
} else {
heap[count] = item;
int current = count;
int par = (current - 1) / 2;
while (true) {
if (heap[par].compareTo(heap[current]) < 0) {
replace(par, current);
current = par;
par = (current - 1) / 2;
} else {
break;
}
}
}
count++;
if (count == size) {
T[] array = (T[]) new Comparable[size * 2];
System.arraycopy(heap, 0, array, 0, size);
heap = array;
size *= 2;
}
}
// 完善delete函数
public void delete() {
heap[0] = heap[--count];
heap[count] = null;
int current = 0;
int left = current * 2 + 1;
int right = current * 2 + 2;
while (true) {
if (heap[left] != null && heap[right] != null && heap[current].compareTo(heap[left]) < 0 && heap[current].compareTo(heap[right]) < 0) {
if (heap[left].compareTo(heap[right]) < 0 || heap[left].compareTo(heap[right]) == 0) {
replace(right, current);
current = left;
} else {
replace(left, current);
current = right;
}
left = current * 2 + 1;
right = current * 2 + 2;
} else if (heap[left] != null && heap[current].compareTo(heap[left]) < 0) {
replace(left, current);
current = left;
left = current * 2 + 1;
right = current * 2 + 2;
} else if (heap[right] != null && heap[current].compareTo(heap[right]) < 0) {
replace(right, current);
current = right;
left = current * 2 + 1;
right = current * 2 + 2;
} else {
break;
}
}
}
private void replace(int initial, int target) {
T value;
value = heap[initial];
heap[initial] = heap[target];
heap[target] = value;
}
// 为了测试方便,完善print函数
public void print() {
for (T value : heap) {
if (value == null) {
break;
}
System.out.print(value + " ");
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zheng-xuzhu/lec07-heap.git
git@gitee.com:zheng-xuzhu/lec07-heap.git
zheng-xuzhu
lec07-heap
lec07-heap
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385