堆排序

记录

//TODO

 

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] arr = { 5, 7, 24, 3463, 1, 3, 51, 7, 9, 10, 3 };
        heapSort(arr, arr.length);
    }

    private static void heapSort(int[] arr, int len) {

        for(int i=0; i<len; i++){
            buildMaxHeap(arr, len-i);
            swap(arr,len-i);
            System.out.println("元素序列为:"+Arrays.toString(arr));
        }

    }

    private static void swap(int[] arr, int len) {
        int temp = arr[0];
        arr[0] = arr[len-1];
        arr[len-1] = temp;
    }

    private static void buildMaxHeap(int[] arr, int len) {
        for (int i = len / 2 - 1; i >= 0; i--) {
            buildHeap(arr, i, len);
        }
    }

    private static void buildHeap(int[] arr, int root, int len) {
        if (root < len) {
            int left = root * 2 + 1;
            int right = root * 2 + 2;
            int max = root;
            if (left < len) {
                if (arr[max] < arr[left]) {
                    max = left;
                }
            }
            if (right<len) {
                if(arr[max] < arr[right]){
                    max = right;
                }
            }
            if(max != root){
                int temp = arr[max];
                arr[max] = arr[root];
                arr[root] = temp;
                buildHeap(arr, max, len);
            }
        }
    }

}
posted @ 2019-12-27 19:41  Yinniora  阅读(218)  评论(0编辑  收藏  举报