diff --git a/Heap.java b/Heap.java new file mode 100644 index 0000000000000000000000000000000000000000..dd6535a552beb51a5e5d252b8d721d8bbab0472b --- /dev/null +++ b/Heap.java @@ -0,0 +1,30 @@ + +public class Heap>{ + 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; + } + + } + + public void delete(T item){ + + } + + public void print(){ + } +} \ No newline at end of file diff --git a/HeapSortDemo/HeapSort.java b/HeapSortDemo/HeapSort.java new file mode 100644 index 0000000000000000000000000000000000000000..0c002f9d33a9acf37b6160160959e14659454e7f --- /dev/null +++ b/HeapSortDemo/HeapSort.java @@ -0,0 +1,76 @@ +package HeapSortDemo; + + +import java.util.Arrays; +import java.util.Scanner; + + +public class HeapSort { + private static int arr[] = new int[20]; + public static int size; + + + public static void print(){ + for (int i = 0; i < size; i++) { + System.out.print(arr[i] + " "); + } + } + public static void main(String[] args) { +// arr= new int[]{1, 2, 4, 6, 8, 5, 9, 7, 65, 10, 12, 26, 34}; + int i; + Scanner scanner = new Scanner(System.in); +// 添加成员 + System.out.println("输入添加的数:"); + while (scanner.hasNextInt()) { + i = scanner.nextInt(); + add(i); + } +// 排序 + heapSort(arr); + System.out.print("排序后:"); + print(); + + } + +// 添加 + public static void add(int i) { + arr[size++] = i; + } + + // 堆排序 + public static void heapSort(int arr[]) { + for (int k = 0; k < arr.length/2; k++) { + int length = arr.length; + //System.out.println("第" + (k+1) +"次比较"); + for (int i = length / 2 - 1; i >= 0; i = (length / 2 - 1)) { + adjustHeap(arr, i, arr.length); + //System.out.println("第" + i + ":" + Arrays.toString(arr)); + if (length%2==1){ + length -= 2; + }else { + --length; + } + } + + } + } + +// 调整位置 + + public static void adjustHeap(int arr[], int i, int length) { + int temp = arr[i]; + for (int j = i * 2 + 1; j < length; j = j * 2 + 1) { + if (j + 1 < length && arr[j] < arr[j + 1]) { //如果左子节点小于右子节点 + j++; + } + if (arr[i] < arr[j]) { + arr[i] = arr[j]; + i = j; +// return; + } else { + break; + } + } + arr[i] = temp; + } +}