根据B站av47196993视频,写的堆排序算法。
基础知识补充
1、二叉树
2、完全二叉树、满二叉树
- 完全二叉树:从根结点到倒数第二层满足完美二叉树,最后一层可以不完全填充,其叶子结点都靠左对齐。
- 满二叉树:所有非叶子结点的度都是2。
3、堆
- 堆中某个节点的值总是不大于或不小于其父节点的值;
- 堆总是一棵完全二叉树。
4、大根堆、小根堆
5、求给定节点arr[i]的父结点和孩子结点公式。
- 求父结点
int p = (i-1)/2
- 求两个孩子节点
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
6、java实现
public class HeapSort {
public static void main(String[] args) {
int tree[] = { 10, 5, 2, 1, 4, 3, 8, 9, 23, 44, 55, 22, 11, 25, 37 };
printSort(tree);
}
public static void printSort(int tree[]) {
int n = tree.length - 1;
int newtree[] = Arrays.copyOf(tree, tree.length);
for (int i = n; i >= 0; i--) {
heapfiy(newtree, (i - 1) / 2, newtree.length);
// 大根堆的根放到最后一位,然后将最后一位输出并砍断。
swap(newtree, 0, i);
System.out.print(newtree[i] + " ");
newtree = Arrays.copyOf(newtree, i);
}
}
public static void heapfiy(int tree[], int i, int n) {
if (i < 0) {
return;
}
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
if (c1 < n && tree[c1] > tree[i]) {
swap(tree, c1, i);
}
if (c2 < n && tree[c2] > tree[i]) {
swap(tree, c2, i);
}
heapfiy(tree, i - 1, n);
}
private static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}