1 Star 0 Fork 44

丘家鑫/lec07-heap

forked from SE-202/lec07-heap 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Heap.java 2.54 KB
一键复制 编辑 原始数据 按行查看 历史
丘家鑫 提交于 2020-12-15 18:32 . 34
public class Heap<T extends Comparable<T>>{
public T[] heap;
public int SIZE;
public int count;
Heap(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 void add (T item){
if(count >= SIZE){
// throw new Exception("Heap Overflow");
System.out.println("Heap Full");
return;
}
// for (int i=0;i<SIZE;i++){
// if(heap[i]==null){
// count=i;
// heap[count] = item;
// }
// else if{
// }
// }
heap[count]=item;
percolateUp(count);
count++;
}
private void percolateUp(int count) {
while(0 < count){
int j = (count - 1) / 2;
int arr=heap[count].compareTo(heap[j]);
if(arr<0){
break;
}
swap(count, j);
count = j;
}
}
public void swap(int i, int j){
T temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
public T delete(){
T temp = heap[0];
heap[0] = heap[--count];
percolateDown(count, 0);
heap[count] = null;
return temp;
}
private int percolateDown(int count, int i) {
int j;
while(i != (j = ProperParent(count, i))){
swap(i, j);
i = j;
}
return i;
}
private int ProperParent(int count, int i) {
return RChildValid(count, i) ? Bigger(Bigger(i, i * 2 + 1), i * 2 + 2) :
LChildValid(count, i) ? Bigger(i, i * 2 + 1) : i;
}
public boolean RChildValid(int n, int i){
if(i * 2 + 2 < n){
return true;
}
return false;
}
public boolean LChildValid(int n, int i){
if(i * 2 + 1 < n){
return true;
}
return false;
}
public int Bigger(int i, int j){
int arr=heap[i].compareTo(heap[j]);
if(j < count){
return arr>0 ? i : j;
}
return i;
}
public void print(){
for(int i=0;i<SIZE;i++){
System.out.print(heap[i]+" ");
}
}
public static void main(String[] args) {
//int a[] ={5,7,10,3,15,8,20,18};
Heap<Integer> heap = new Heap<Integer>(10);
heap.add(1);
heap.print();
System.out.println(" ");
heap.add(2);
heap.print();
System.out.println(" ");
heap.add(3);
heap.print();
System.out.println(" ");
heap.add(5);
heap.print();
System.out.println(" ");
heap.add(4);
heap.print();
System.out.println(" ");
heap.add(10);
heap.print();
System.out.println(" ");
heap.delete();
heap.print();
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/qjx1654/lec07-heap.git
git@gitee.com:qjx1654/lec07-heap.git
qjx1654
lec07-heap
lec07-heap
master

搜索帮助