it_worker365

   ::  ::  ::  ::  :: 管理
/**
 * Created by itworker365 on 5/11/2017.
 *
 * 堆结构可以视为一颗完全二叉树,除了最后一层节点其余都是满的,所以可算出parent(i)=i/2  leftchild(i)=2*i  rightchild=2*i + 1
 * 因为根节点的值都大于两个子节点,因为其子女节点的序号都大于n,所以n/2 + 1 ~ n都是叶节点,因此构建堆就在1 ~ n/2 进行
 * 排序时每次将最大元素与队尾元素互换后将堆大小-1,以此类推
 */
public class HeapSort1 {
    public static void main(String[] args) {
        //期待结果,1234579
        int[] array = { 2,3,1,5,4,9,7};
        System.out.println("Before heap:");
        printArray(array);
        //
        buildMaxHeap(array);
        for (int i = array.length - 1; i >= 1; i--) {
            swamp(array, 0, i);
            maxHeap(array, i, 0);
        }
        System.out.println("After heap sort:");
        printArray(array);
    }
    private static void buildMaxHeap(int[] array) {
        if (array == null || array.length <= 1) {
            return;
        }
        //构建非叶节点
        int half = array.length / 2;
        for (int i = half; i >= 0; i--) {
            maxHeap(array, array.length, i);
        }
    }
    private static void maxHeap(int[] array, int heapSize, int index) {
        int left = index * 2 + 1;
        int right = index * 2 + 2;
        //计算左右儿子是否符合堆性质,找出父/左/右的最大元素
        int largest = index;
        if (left < heapSize && array[left] > array[index]) {
            largest = left;
        }

        if (right < heapSize && array[right] > array[largest]) {
            largest = right;
        }
        //交换并继续调整交换后的子顺序
        if (index != largest) {
            swamp(array, index, largest);
            maxHeap(array, heapSize, largest);
        }
    }

    public static void printArray(int[] array) {
        System.out.print("{");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            if (i < array.length - 1) {
                System.out.print(", ");
            }
        }
        System.out.println("}");
    }
    public static void swamp(int[] array, int index1, int index2) {
        int temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    }
}

 

posted on 2017-05-11 10:50  it_worker365  阅读(189)  评论(0编辑  收藏  举报