package com.wang.principle; public class Test2 { public static void main(String[] args) { int[] arr = {49, 38, 65, 97, 76, 13, 27, 50}; //int[] c = { 13, 38, 65, 97, 76, 13, 2, 50 };//稳定性判断 heapSort(arr); for (int i : arr) { System.out.print(i+" "); } } public static void heapSort(int[] arr) { if (arr == null && arr.length < 2) { return; } //先构建大顶堆 for (int i = 0; i < arr.length; i++) { headInsert(arr, i); } int size = arr.length; //每次选大顶堆root节点 size不断减1 swap(arr, 0, --size); while (size > 0) { headify(arr, 0, size); swap(arr, 0, --size); } } //上升 public static void headInsert(int[] arr, int cur) { while (arr[cur] > arr[(cur - 1) / 2]) { swap(arr, cur, (cur - 1) / 2); cur = (cur - 1) / 2; } } //下降 public static void headify(int[] arr, int index, int heapSize) { int left = index * 2 + 1; while (left < heapSize) { int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;//最大值下标 largest = arr[largest] > arr[index] ? largest : index; if (largest == index) { break; } swap(arr, largest, index); index = largest; left = index * 2 + 1; } } private static void swap(int[] arr, int x, int y) { int temp = arr[x]; arr[x] = arr[y]; arr[y] = temp; } }
浙公网安备 33010602011771号