diff --git "a/\344\275\234\344\270\232/Heap.java" "b/\344\275\234\344\270\232/Heap.java" new file mode 100644 index 0000000000000000000000000000000000000000..2b1c4b189e56456292c2240cd2dd20bbe3a8e9e3 --- /dev/null +++ "b/\344\275\234\344\270\232/Heap.java" @@ -0,0 +1,84 @@ +public class Heap>{ + public T[] heap; + public int SIZE; + public int count; + + Heap(int size){ + SIZE=size; + heap=(T[])new Comparable[SIZE]; + count=0; + } + public void add (T item){ + if(count>=SIZE){ + System.out.println("Heap Full"); + return; + } + heap[count]=item; + percloateUp(count); + count++; + } + private void percloateUp(int count){ + while(count>0){ + int j=(count-1)/2; + int arr=heap[count].compareTo(heap[j]); + if(arr<0){ + break; + } + swap(count,j); + count=j; + } + } + private void swap(int i,int j){ + T temp=heap[i]; + heap[i]=heap[j]; + heap[j]=heap[i]; + } + public void print(){ + for (T i:heap){ + System.out.print(i+"\t"); + } + } + public T delete(){ + T tempmax=heap[0]; + heap[0]=heap[--count]; + percolateDown(count,0); + heap[count]=null; + return tempmax; + } + 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; + } +} + diff --git "a/\344\275\234\344\270\232/Main.java" "b/\344\275\234\344\270\232/Main.java" new file mode 100644 index 0000000000000000000000000000000000000000..535d6eab1f49e19cfdc30b9dbd56af05ca487440 --- /dev/null +++ "b/\344\275\234\344\270\232/Main.java" @@ -0,0 +1,18 @@ +class Main { + public static void main(String[] args){ + Heap heap = new Heap(10); + heap.add(0); + + heap.add(2); + heap.add(9); + heap.add(4); + heap.add(3); + heap.add(10); + heap.add(6); + heap.add(5); + heap.print(); + + heap.delete(); + heap.print(); + } +} \ No newline at end of file