堆结构和堆排序

java 复制代码
import java.io.*;
public class Main{
    public static int MAXN = 100001;
    public static int[] arr = new int[MAXN];
    public static int n;

    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
        StreamTokenizer in = new StreamTokenizer(br);

        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

        in.nextToken();
        n = (int)in.nval;

        for(int i = 0;i < n;i++){
            in.nextToken();
            arr[i] = (int)in.nval;
        }

        //堆排序
         heapSort1(arr);
		// heapSort2(arr);
        //输出排序后的数组
        for(int i = 0;i< n-1;i++){
            out.print(arr[i] +" ");
        }
        out.print(arr[n-1]);

        out.flush();
        out.close();
        br.close();
    }


    //heapInsert (i位置的数,向上调整大根堆)
    public static void heapInsert(int i){
        while(arr[i] > arr[(i-1)/2]){
            swap(arr,i,(i-1)/2);
            i = (i-1)/2;
        }
    }   
    //heapify (i位置的数,向下调整大根堆)
    //当前堆的大小为size
    public static void heapify(int i,int size){
        int l = i*2 +1;
        while(l<size){
             //比较i的左孩子2i+1 和 右孩子2i+2,哪个大,选出更大的孩子下标
           int best = (l + 1)<size && arr[l] < arr[l+1] ? (l+1) : l;

            //再比较i和更大的孩子之间哪个大
            best = arr[i] >arr[best] ? i : best;
            if(best == i){
                break;
            }
            swap(arr ,i , best);
            i = best;
            l = i*2 +1;  
        }
    }
    
    //heapSort1为从顶到底建立大根堆然后排序
    //从顶到底建立大根堆 O(n*logn)
    //依次弹出堆内最大值并排好序O(n*logn)
    //整体时间复杂度O(n*logn)
    public static void heapSort1(int arr[]){
        for(int i=0;i<n;i++){
            heapInsert(i);
        }
        int size = n;
        while(size>1){
            swap(arr,0,--size);
            heapify(0,size);
        }
    }
    //heapSort2为从底到顶建堆然后排序
    //从底到顶建立大根堆O(n)
    //依次弹出堆内最大值并排好序 O(n*logn)
    //整体时间复杂度O(n*logn)
    public static void heapSort2(int arr[]){
        for(int i = n -1;i>=0;i--){
            heapify(i,n);
        }
        int size = n;
        while (size > 1) {
			swap(arr,0, --size);
			heapify(0, size);
		}
    }

    //swap函数
    public static void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
相关推荐
没有bug.的程序员2 小时前
服务安全:内部服务如何防止“裸奔”?
java·网络安全·云原生安全·服务安全·零信任架构·微服务安全·内部鉴权
一线大码2 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
前端小L2 小时前
贪心算法专题(十):维度权衡的艺术——「根据身高重建队列」
javascript·算法·贪心算法
方得一笔2 小时前
自定义常用的字符串函数(strlen,strcpy,strcmp,strcat)
算法
weixin_440730502 小时前
java数组整理笔记
java·开发语言·笔记
weixin_425023002 小时前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码2 小时前
Java 8-25 各个版本新特性总结
java·后端
Xの哲學2 小时前
Linux SMP 实现机制深度剖析
linux·服务器·网络·算法·边缘计算
2501_906150563 小时前
私有部署问卷系统操作实战记录-DWSurvey
java·运维·服务器·spring·开源
wuk9983 小时前
使用PCA算法进行故障诊断的MATLAB仿真
算法·matlab