目录
- public class HeapSortArray {
- public HeapSortArray() {
- }
-
- public static void main(String[] args) {
- int[] arr = new int[]{4, 6, 8, 5, 9, 15, 1, 24, 56, 3, 100};
- int[] arr1 = new int[]{12, 8, 1, 13, 14, 15, 7};
- HeapSortArray sort = new HeapSortArray();
- sort.heapSort(arr, sort);
- }
-
- public void heapSort(int[] arr, HeapSortArray sort) {
- int i;
- //依次遍历非叶子节点,保证非叶子节点的符合根节点>左右子节点的要求
- for(i = arr.length / 2 - 1; i >= 0; --i) {
- sort.adjustHeap(arr, i, arr.length);
- }
-
- //首先进行依次转换操作,接着依次从0
- for(i = arr.length - 1; i > 0; --i) {
- int temp = arr[i];
- arr[i] = arr[0];
- arr[0] = temp;
- //注意i代表的是数组的长度,随着每次程序的完成后数组的长度会依次减1
- sort.adjustHeap(arr, 0, i);
- }
-
- System.out.println(Arrays.toString(arr));
- }
-
- public void adjustHeap(int[] arr, int i, int length){
- int temp = arr[i];
- for (int j = 2*i + 1; j < length; j = 2*j+1 ) {
- //如果当前根节点存在右子节点,并且右子结点的值>左子节点,说明是右子结点跟根节点交换
- if (j + 1 < length && arr[j] < arr[j+1]){
- j++;
- }
- if (arr[j] < temp){
- break;
- }
- //进入这里说明跟节点不是最大的,需要跟左右节点交换
- arr[i] = arr[j];
- //将j的值赋值给i,需要知道最后将temp赋值给哪个数组索引
- i = j;
- }
- arr[i] = temp;
- }
- }