堆排序 Java

堆排序的原理

基本原理也是选择排序,只是不在使用遍历的方式查找无序区间的最大的数,而是通过堆来选择无序区间的最大的 数。
注意: 排升序要建大堆;排降序要建小堆。
在这里插入图片描述

堆排序实现

升序为例

public class heapSort {
    public static void heapSort(int[] array) {
    	//根据给的数组来创建堆
        creatHeap(array);
        //循环交换第一个元素倒数第i个元素
        //并且将新的顺序进行调整以满足堆的性质
        for (int i = 0; i < array.length; i++) {
            swap(array, 0, array.length - 1 - i);
            shiftDown(array, array.length - 1- i, 0);
        }
    }
	
	//创建堆
    private static void creatHeap(int[] array) {
        for (int i = (array.length - 1) / 2; i >= 0; i--) {
            shiftDown(array, array.length, i);
        }
    }

	//向下调整
    private static void shiftDown(int[] array, int size, int index) {
        int parent = index;
        int child = parent * 2 + 1;
        while (child < size) {
            if (child + 1 < size && array[child] < array[child + 1]) {
                child = child + 1;
            }
            if (array[parent] < array[child]) {
                swap(array, parent, child);
            } else {
                break;
            }
            parent = child;
            child = parent * 2 + 1;
        }
    }

    private static void swap(int[] array, int x, int y) {
        int temp = array[x];
        array[x] = array[y];
        array[y] = temp;
    }

    public static void main(String[] args) {
        int[] array = {9, 5, 2, 7, 3, 6, 8, 1};
        heapSort(array);
        System.out.println(Arrays.toString(array));
    }
}

性能分析

时间复杂度空间复杂度
O(n * log(n))O(1)
数据不敏感数据不敏感

稳定性:不稳定

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值