Java 大堆排序從0開始
阿新 • • 發佈:2019-02-18
public class HeapSortFrom0 { /* 51 46 20 18 -10 82 65 30 77 97 101 85 */ /** * 構建大頂堆 */ public static void adjustHeap(int[] a, int i, intlen) { int temp; temp = a[i];//最後一個節點的父節點 for (int j = 2 * i + 1; j <= len; j = 2 * j + 1) {// 沿關鍵字較大的孩子結點向下篩選 if (j + 1 <= len && a[j] < a[j + 1]) ++j; // j為關鍵字中較大記錄的下標 if (temp >= a[j]) break; a[i] = a[j]; i = j; a[i] = temp; } } public static voidheapSort(int[] a) { int i; for (i = ((a.length - 1) - 1) / 2; i >= 0; i--) {// 構建一個大頂堆 adjustHeap(a, i, a.length - 1); } //System.out.println(Arrays.toString(a)); //System.exit(0); for (i = a.length - 1; i > 0; i--) {// 將堆頂記錄和當前未經排序子序列的最後一個記錄交換 int temp = a[0]; a[0] = a[i]; a[i] = temp; adjustHeap(a, 0, i - 1);// 將a中前i-1個記錄重新調整為大頂堆 } } public static void main(String[] args) { int a[] = {51, 46, 20, 18, -10, 82, 65, 30, 77, 97,101,85}; heapSort(a); System.out.println(Arrays.toString(a)); } }