堆排序Java实现(超简)

堆排序

根据阿顾同学的《堆排序算法(图解详细流程)》修改的,详细算法可以链接查看,有问题可以指出,谢谢~

Java实现代码

public class Sort {
    public static void main(String[] args) {
        int[] array = {9, 8, 7, 6, 11, 4, 13, 11,3, 2, 1, 0, -1, -2, -3};

		// test 堆排序
        heapSort(array);
        System.out.println(Arrays.toString(array));
    }

    // 堆排序
    public static void heapSort(int[] array){
        // 创建一个大顶堆
        heapInsert(array, array.length - 1);
        int len = array.length - 1;

        while(len > 0){
            // len == 1是说明数组中还有两个数无序
            swap(array, 0, len);
            len--;
            heapInsert(array, len);
        }
    }
	
	// 将数组array中无序部分调整为大顶堆,len为无序数组的最大下标
    public static void heapInsert(int[] array, int len){
        for(int i = 0; i <= len; i++){
            int curIndex = i;
            int fatherIndex = (curIndex - 1) / 2;

            while(array[curIndex] > array[fatherIndex]){
                swap(array, curIndex, fatherIndex);
                // 当交换后,需要比较新的array[curIndex]和其父节点值的大小,直至无法交换
                curIndex = fatherIndex;
                fatherIndex = (curIndex - 1) / 2;
            }
        }
    }

	// 交换
    public static void swap(int[] array, int i, int j){
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值