-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathDeapSort.java
54 lines (47 loc) · 1.17 KB
/
DeapSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package leetcode.priorityqueue;
import java.util.Arrays;
/**
* 堆排序
*
* @author FangYuan
* @since 2023-10-24 21:03:07
*/
public class DeapSort {
public static void main(String[] args) {
// 索引 0 处值不用
int[] nums = {-1, 9, 5, 8, 4, 6, 2, 1};
new DeapSort().sort(nums);
System.out.println(Arrays.toString(nums));
}
public void sort(int[] nums) {
int n = nums.length - 1;
// 1. 建堆
for (int i = n / 2; i > 0; i--) {
sink(nums, i, n);
}
// 2. 下沉排序
while (n > 1) {
swap(nums, n, 1);
sink(nums, 1, --n);
}
}
private void sink(int[] nums, int i, int n) {
while (i * 2 <= n) {
int max = i * 2;
if (max + 1 <= n && nums[max + 1] > nums[max]) {
max++;
}
if (nums[i] < nums[max]) {
swap(nums, i, max);
i = max;
} else {
break;
}
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}