1.这篇文章讲的很好:
https://www.cnblogs.com/chengxiao/p/6129630.html#
2.下面这两个视频讲的也很清晰:
https://www.acfun.cn/v/ac17519479
https://www.acfun.cn/v/ac17519437
3. 堆排序代码
1 package cn.sun.it.review; 2 3 import java.util.Arrays; 4 import java.util.Scanner; 5 6 public class HeapSort { 7 8 public static void main(String[] args) { 9 // 测试数据:49,38,65,97,76,13,27,49 10 System.out.println("请输入若干个整数,以逗号分隔:"); 11 Scanner sc = new Scanner(System.in); 12 String strNums = sc.nextLine(); 13 String[] tempArrNums = strNums.split(","); 14 int[] arr = new int[tempArrNums.length]; 15 for (int i = 0; i < arr.length; i++) { 16 arr[i] = Integer.valueOf(tempArrNums[i]); 17 } 18 System.out.println("排序前:" + Arrays.toString(arr)); 19 heapSort_v1(arr, arr.length); 20 System.out.println("排序后:" + Arrays.toString(arr)); 21 22 } 23 24 private static void heapSort_v1(int[] arr, int n) { 25 int i; 26 int temp; 27 for (i = n / 2 - 1; i >= 0; --i) { // 构造初始堆 28 sift(arr, i, n - 1); 29 } 30 for (i = n - 1; i > 0; --i) { 31 temp = arr[0]; 32 arr[0] = arr[i]; 33 arr[i] = temp; 34 sift(arr, 0, i - 1); 35 } 36 } 37 38 private static void sift(int[] arr, int low, int high) { 39 int i = low, j = 2 * i + 1; 40 int temp = arr[i]; 41 while (j <= high) { 42 if (j < high && arr[j] < arr[j + 1]) { 43 ++j; 44 } 45 if (temp < arr[j]) { 46 arr[i] = arr[j]; 47 i = j; 48 j = 2 * i + 1; 49 } else { 50 break; 51 } 52 } 53 arr[i] = temp; 54 } 55 }
4. 堆排序性能
(4.1)空间复杂度:O(1)
(4.2)时间复杂度:建堆时间复杂度为O(n), 最好、最坏和平均时间复杂度均为O(nlog2n)
(4.3)稳定性:不稳定