auto commit
This commit is contained in:
parent
845d610630
commit
712e6af87f
34
notes/算法.md
34
notes/算法.md
|
@ -1,5 +1,4 @@
|
|||
<!-- GFM-TOC -->
|
||||
* [一、前言](#一前言)
|
||||
* [二、算法分析](#二算法分析)
|
||||
* [数学模型](#数学模型)
|
||||
* [ThreeSum](#threesum)
|
||||
|
@ -35,7 +34,7 @@
|
|||
<!-- GFM-TOC -->
|
||||
|
||||
|
||||
# 一、前言
|
||||
# 一、前言
|
||||
|
||||
本文实现代码以及测试代码放在 [Algorithm](https://github.com/CyC2018/Algorithm)
|
||||
|
||||
|
@ -1073,30 +1072,37 @@ public T delMax() {
|
|||
<div align="center"> <img src="../pics//1f039a45-6b91-4f31-a2c2-6c63eb8bdb56.png" width="300"/> </div><br>
|
||||
|
||||
```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<T extends Comparable<T>> extends Sort<T> {
|
||||
/**
|
||||
* 数组第 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;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user