diff --git a/Heap.java b/Heap.java new file mode 100644 index 0000000000000000000000000000000000000000..93a2b32525e989e81280f65465c3d801883908e7 --- /dev/null +++ b/Heap.java @@ -0,0 +1,70 @@ +public class Heap> { + private T[] heap; + private int size; + private int count; + + Heap(int size) { + this.size = size + 1; + // reference: https://stackoverflow.com/questions/34827626/cannot-be-cast-to-ljava-lang-comparable + heap = (T[]) new Comparable[this.size]; + count = 0; + } + + public void add(T item) { + if (count >= size) { + // throw new Exception("Heap Overflow"); + System.out.println("Heap Full"); + return; + } + heap[++count] = item; + int position = count; + while ((position >> 1) >= 1 && heap[position].compareTo(heap[position >> 1]) > 0) { + //成立交换位置 + T t = heap[position]; + heap[position] = heap[position >> 1]; + heap[position >> 1] = t; + position = position >> 1; + } + } + + public T removeTop() { + if (isNull()) { + System.out.println("Heap Null"); + return null; + } + T returnData = heap[1]; + heap[1] = heap[count--];//将最后一个拿到第一位 + int position = 1; + while (true) { + int positionBackup = position; + if ((2 * position) <= count && heap[2 * position].compareTo(heap[positionBackup]) > 0) { + positionBackup = 2 * position; + } + if ((2 * position + 1) <= count && heap[2 * position + 1].compareTo(heap[positionBackup]) > 0) { + positionBackup = 2 * position + 1; + } + if (positionBackup == position) { + break;//无需交换退出循环 + } + T t = heap[position]; + heap[position] = heap[positionBackup]; + heap[positionBackup] = t; + position = positionBackup; + } + return returnData; + } + + + //isNull + public boolean isNull() { + return count == 0; + } + + public void print() { + String str = ""; + for (int i = 1; i < count; i++) { + str += heap[i] + " "; + } + System.out.println(str); + } +} \ No newline at end of file diff --git a/HeapSort.java b/HeapSort.java new file mode 100644 index 0000000000000000000000000000000000000000..2395da68a7d029217784d3fe62da1c6117beb6a5 --- /dev/null +++ b/HeapSort.java @@ -0,0 +1,17 @@ +public class HeapSort> { + + + public T[] sort(T[] array) { + int length = array.length; + Heap heap = new Heap(length); + for (int i=0;i