堆结构和堆排序

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;
    }
}
相关推荐
小蒜学长13 分钟前
微信小程序-高校自习室管理系统(代码+数据库+LW)
java·spring boot·后端·微信小程序·自习室管理
Nil20820 分钟前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年25 分钟前
AI Agent、自动化与未来工作
人工智能·算法·架构
鸥梨菌Honevid26 分钟前
UVM 中 REQ 和 RSP 类型详解:从通信模型到 item_done 与 put_response
java·前端·servlet
瑞克-桑切斯34 分钟前
真实企业场景 运维安全与管理
java·网络·github
牧羊人.33335 分钟前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
Nil2081 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
老板一杯拿铁1 小时前
Java 八股文面试详解:从基础到进阶的全面梳理
java·面试
const_qiu1 小时前
第 2.5 章 2.5.4-2.5.5:JWT 双 Token 与声明式权限守卫
java·人工智能
bug菌1 小时前
一个周末就想把短链服务推到 10 万 QPS,真能靠加 Redis 做到吗?
java·redis·go