package com.xiejianjun.day09;
import java.util.Arrays;
/**
* @author bilibilidick
* @version 2022 04
* @date 2022/4/24 12:15
*/
public class Heapsort {
public static void main(String[] args) {
int[] tree = {1, 2, 3, 4, 5, 6, 7};
build_heap(tree);
System.out.println("层序遍历此数组转化为大顶堆后的结果:" + Arrays.toString(tree));
}
// 交换两个结点,因为能执行找个方法就代表已经判断过数组越界的问题了,故不在此判断越界
public static void swap(int[] tree,int parent,int child) {
int temp = 0;
temp = tree[parent];
tree[parent] = tree[child];
tree[child] = temp;
}
// 从下到上构建大顶堆
public static void build_heap(int[] tree) {
int last_node = tree.length - 1;
int last_parent = (last_node - 1) / 2;
for (int i = last_parent; i >= 0 ; i--) {
heapify(tree, i, tree.length);
}
}
// 构造顶堆的方法,只对被打乱的结点的子树做递归,所以heapify(max)
public static void heapify(int[] tree, int i, int n) {
if (i < n) {
int max = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && tree[left] > tree[max]) {
max = left;
}
if (right < n && tree[right] > tree[max]) {
max = right;
}
if (i != max) {
swap(tree, i, max);
heapify(tree,max,n);
}
}
}
}
构造大顶堆
最新推荐文章于 2023-04-04 15:30:33 发布