关于堆排序,JAVA实现
话不多说,直接上代码
堆排序,来自某2021年准备找暑期实习的网友的code
// 自己写的实现,不是最完美的实现
public class HeapSort {
/**
* 堆排序
* @param arr
* @param <T>
*/
public static <T extends Comparable<? super T>> void heapSort(T[] arr) {
for (int i = 1; i < arr.length; ++i) generateMaxHeap(arr, i); //构建最大堆
for (int i = arr.length - 1; i > 0; --i) deleteHead(arr, i); //删除顶端元素并将最大值转到末尾
}
/**
* 删除顶点
* @param arr
* @param index
* @param <T>
*/
private static <T extends Comparable<? super T>> void deleteHead(T[] arr, int index) {
T temp = arr[index];
arr[index] = arr[0];
int hole = 0;
while (getLeftSonIndex(hole) < index) {
int leftSon = getLeftSonIndex(hole);
int newHole = leftSon;
int rightSon = leftSon + 1;
if (rightSon < index && arr[rightSon].compareTo(arr[leftSon]) > 0) newHole = rightSon;
if (temp.compareTo(arr[newHole]) > 0) break;
else {
arr[hole] = arr[newHole];
hole = newHole;
}
}
arr[hole] = temp;
}
/**
* 建最大堆
* @param arr
* @param index
* @param <T>
*/
private static <T extends Comparable<? super T>> void generateMaxHeap(T[] arr, int index) {
while (index > 0) {
int fatherIndex = getFatherIndex(index);
if (arr[index].compareTo(arr[fatherIndex]) > 0) {
swap(arr, index, fatherIndex);
index = fatherIndex;
}
else return;
}
}
/**
* 获取左儿子节点
* @param i
* @return
*/
private static int getLeftSonIndex(int i) {
return (i << 1) + 1;
}
/**
* 获取父节点
* @param i
* @return
*/
private static int getFatherIndex(int i) {
return i - 1 >> 1;
}
/**
* 交换索引数据
* @param arr
* @param i
* @param j
* @param <T>
*/
private static <T extends Comparable<? super T>> void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
没错,那位找暑期实习的网友就是本人