版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33824312/article/details/77851988
package com.duobang.headSort;
import java.util.Arrays;
import java.util.Random;
public class MyHeapSort {
public static void main(String[] args) {
//随机产生count个元素的数组
Random rd = new Random();
int count = 10;
int[] a = new int[count];
for (int i = 0; i < count; i++) {
a[i] = rd.nextInt(count);
}
System.out.println("初始数组:" + Arrays.toString(a));
heapSort(a);
System.out.println("排序后数组:" + Arrays.toString(a));
}
//堆排序
private static void heapSort(int[] a) {
//建立大根堆
buildMaxHeap(a);
//排序:将大根堆中最大的元素放在最后,再次调节大根堆.
for (int i = a.length - 1; i > 0 ; i--) {
//交换头尾元素
swap(a,0,i);
//调整大根堆
adjustDownToUp(a,0,i);
}
//调整会出现第一个元素比第二个元素大的问题,所以交换
if (a[0] > a[1]) {
swap(a,0,1);
}
}
//将root为根节点的元素调整为大根堆
private static void adjustDownToUp(int[] a, int root, int last) {
int tmp = a[root];
//调整大根堆
for (int i = root * 2 + 1; i < last - 1; i = i * 2 + 1) {
//取root的左右孩子中最大的一个
if (i < last && a[i] < a[i+1]) {
i++;
}
//最大的孩子与根节点比较
if (tmp > a[i]) {
break;
}else{
a[root] = a[i];//将大的孩子放在根节点的位子
root = i;//根节点变为当前大的孩子的位置
}
}
//将根节点放在root的位置
a[root] = tmp;
}
//交换下标为i和i2两个元素的位置
private static void swap(int[] a, int i, int i2) {
a[i] = a[i] ^ a[i2];
a[i2] = a[i] ^ a[i2];
a[i] = a[i] ^ a[i2];
}
//建立大根堆
private static void buildMaxHeap(int[] a) {
int len = a.length;
//从最后一个节点开始调整大根堆
for (int i = (len - 1 - 1)/2; i >= 0; i--) {
//将父节点是i的这棵树调节成一棵大根堆
adjustDownToUp(a,i,len);
}
}
}