做题笔记12.6,堆排序

这篇博客主要介绍了如何实现堆排序算法,针对给定长度为n的数组,要求在O(nlogn)的时间复杂度内完成升序排序,且空间复杂度为O(n)。博主分享了自己的解题思路,专注于提升对堆排序的理解和实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

给定一个长度为 n 的数组,请你编写一个函数,返回该数组按升序排序后的结果。

数据范围: 0≤n≤1000000,数组中每个元素都满足 0≤val≤1000000000

要求:空间复杂度 O(n)O(n),时间复杂度 O(nlogn)O(nlogn)

解题思路:重点练一下自己不熟悉的吧,今天写heapSort

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 将给定数组排序
     * @param arr int整型一维数组 待排序的数组
     * @return int整型一维数组
     */
    public int[] MySort (int[] arr) {
        // write code here
        if(arr.length == 1 || arr.length == 0){
            return arr;
        }
        heapSort(arr, arr.length);
        return arr;
    }
    
    //建堆buildMaxHeap(树,节点总数)
    public void buildMaxHeap(int[]tree, int n){
        int last = n -1;
        int parent = (last-1)/2;
        for(int i = parent; i >= 0; i--){
            heapify(tree, n, i);
        }
    }
    
    //HeapSort实现
    public void heapSort(int[] tree, int n){
        buildMaxHeap(tree, n);
        for(int i = n-1; i >= 0; i--){
            swap(tree, 0, i);
            heapify(tree, i, 0);
        }
    }
    
    //HelperFunction: Swap
    public void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    //对单个父节点进行堆化操作heapify(树,节点总数,操作的节点)
    //操作持续到堆的结构在交换之后依然稳定
    public void heapify(int[] tree, int n, int i){
        if(i >= n){
            return;
        }
        int child1 = i*2+1;
        int child2 = i*2+2;
        int max = i;
        if(child1 < n && tree[child1] > tree[max]){
            max = child1;
        }
        if(child2 < n && tree[child2] > tree[max]){
            max = child2;
        }
        if(max != i){
            swap(tree, max, i);
            heapify(tree, n, max);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值