堆排序

package com.algorithm.sort;

import java.util.Arrays;

/**
 * Created by louis on 2015/3/17.
 */
public class HeapSort {
    private static int heapSize=0;

    public static void maxHeapify(int[] arr, int i) {
        int l = 2 * i;  // left node
        int r = 2 * i + 1;  // right node
        int max = i;
        if (l <= heapSize && arr[l] > arr[i]) {
            max = l;
        }
        if (r <= heapSize && arr[r] > arr[max]) {
            max = r;
        }
        if (max != i) {
            swap(arr, max, i);
            maxHeapify(arr, max);
        }
    }

    public static void buildMaxHeap(int[] arr) {
        heapSize= arr.length-1;
        for (int i = heapSize / 2; i >= 0; i--) {
            maxHeapify(arr, i);
        }
    }

    public static void heapSort(int[] arr) {
        buildMaxHeap(arr);
        for (int i = heapSize; i >= 0; i--) {
            swap(arr, 0, i);
            --heapSize;
            maxHeapify(arr, 0);
            System.out.println(String.format("step %d: %s",i,Arrays.toString(arr)));
        }
    }

    public static void swap(int[] data, int i, int j) {
        int temp = data[i];
        data[i] = data[j];
        data[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {7, 11, 3, 4, 9, 2, 18, 1};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值