代码拉取完成,页面将自动刷新
同步操作将从 SE-202/lec07-heap 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
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();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。