diff --git a/notes/算法.md b/notes/算法.md index d2a1c63f..0b99eb7f 100644 --- a/notes/算法.md +++ b/notes/算法.md @@ -1,5 +1,4 @@ -* [一、前言](#一前言) * [二、算法分析](#二算法分析) * [数学模型](#数学模型) * [ThreeSum](#threesum) @@ -35,7 +34,7 @@ -# 一、前言 + # 一、前言 本文实现代码以及测试代码放在 [Algorithm](https://github.com/CyC2018/Algorithm) @@ -1073,30 +1072,37 @@ public T delMax() {

```java -public class HeapSort { - public static void sort(Comparable[] a) { - int N = a.length - 1; - for (int k = N / 2; k >= 0; k--) - sink(a, k, N); +public class HeapSort> extends Sort { + /** + * 数组第 0 个位置不能有元素 + */ + @Override + public void sort(T[] nums) { + int N = nums.length - 1; + for (int k = N / 2; k >= 1; k--) + sink(nums, k, N); while (N > 1) { - swap(a, 1, N--); - sink(a, 1, N); + swap(nums, 1, N--); + sink(nums, 1, N); } } - - private static void sink(Comparable[] a, int k, int N) { + private void sink(T[] nums, int k, int N) { while (2 * k <= N) { int j = 2 * k; - if (j < N && less(a, j, j + 1)) + if (j < N && less(nums, j, j + 1)) j++; - if (!less(a, k, j)) + if (!less(nums, k, j)) break; - swap(a, k, j); + swap(nums, k, j); k = j; } } + + private boolean less(T[] nums, int i, int j) { + return nums[i].compareTo(nums[j]) < 0; + } } ```