import java.util.Arrays;
public class Test {
private static void swap(int[] arr, int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
private static int parent(int i) {
return (i - 1) >> 1;
}
private static int left(int i) {
return (i << 1) + 1;
}
private static int right(int i) {
return (i << 1) + 2;
}
private static void insert(int[] arr, int i) {
int data = arr[i];
int parent;
while (i != 0) {
parent = parent(i);
if (arr[parent] < data) {
arr[i] = arr[parent];
i = parent;
} else {
break;
}
}
arr[i] = data;
}
private static void heapify(int[] arr, int length) {
int i = 0, left, right;
while (i < length && (left = left(i)) < length) {
int max = i;
if (arr[left] > arr[max]) {
max = left;
}
if ((right = right(i)) < length && arr[right] > arr[max]) {
max = right;
}
if (i != max) {
swap(arr, i, max);
i = max;
} else {
break;
}
}
}
private static void heapSort(int[] arr) {
for (int i = 1; i < arr.length; ++ i) {
insert(arr, i);
}
for (int i = arr.length - 1; i > 0; -- i) {
swap(arr, 0, i);
heapify(arr, i);
}
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 5, 7, 0, 1, 2, 10, 9};
heapSort(arr);
Arrays.stream(arr).forEach(System.out::println);
}
}
来源:51CTO
作者:天一涯51CTO
链接:https://blog.51cto.com/tianyiya/2466794