import java.util.Arrays;
public class DuiSort {
public static void main(String[] args) {
int[] arr = {4, 6, 5, 8, 9, 3, 7, 2, 10,0,1,-99};
dui(arr);
}
public static void dui(int[] arr) {
System.out.println("堆排序:");
int index = arr.length;
for (int j = 0; j < arr.length - 1; j++) {
for (int i = index / 2 - 1; i >= 0; i--) {
creatDui(arr, i, index);
}
int temp = arr[0];
arr[0] = arr[index - 1];
arr[index - 1] = temp;
index--;
}
System.out.println(Arrays.toString(arr));
}
//构建大顶堆
public static void creatDui(int[] arr, int i, int length) {
int temp = arr[i];
for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {
if (k + 1 < length && arr[k] < arr[k + 1]) {
k++;
}
if (arr[k] > arr[i]) {
arr[i] = arr[k];
i = k;
} else {
break;
}
}
arr[i] = temp;
}
}
java数据结构,堆排序
最新推荐文章于 2024-08-16 23:08:28 发布