当前位置: 首页 > news >正文

Java堆排序

目录

  • PriorityQueue
  • 自己实现

PriorityQueue

public class PriorityQueueMain {public static void main(String[] args) {int[] temp = {40, 2, 33, 26, 35, 8, 8, 26, 29, 2};PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();for (int i = 0; i < temp.length; i++) {priorityQueue.offer(temp[i]);}while (!priorityQueue.isEmpty()) {System.out.format("%d ", priorityQueue.poll());}}
}

自己实现

详细原理,只是在push的时候他写错了

public class ArraySmallHeap {public static void main(String[] args) {int[] temp = {40, 2, 33, 26, 35, 8, 8, 26, 29, 2};heap = new int[temp.length];for (int j : temp) {push(j);}for (int i = 0; i < temp.length; i++) {System.out.format("%d ", pop());}}private static int[] heap;private static int size;private static void down(int k) {int t = k;int l = k << 1, r = (k << 1) + 1;if (l <= size && heap[t] > heap[l]) {t = l;}if (r <= size && heap[t] > heap[r]) {t = r;}if (t != k) {int temp = heap[k];heap[k] = heap[t];heap[t] = temp;down(t);}}private static void up(int k) {int u = k / 2;if (u >= 1 && heap[k] < heap[u]) {int temp = heap[k];heap[k] = heap[u];heap[u] = temp;up(u);}}public static void push(int v) {heap[++size] = v;up(size);}public static int pop() {int v = heap[1];heap[1] = heap[size--];down(1);return v;}
}
http://www.lryc.cn/news/113784.html

相关文章:

  • GitHub的基本使用教程
  • objectMapper.configure 方法的作用和使用
  • 面试热题(x的平方根)
  • 食品溯源合约 -- 智能合约实例
  • SAP系统中二代增强提供了4中增强函数的查找方法
  • RabbitMQ-SpringBoot2
  • MyBatis核心 - SqlSession如何通过Mapper接口生成Mapper对象
  • 【Git】标签管理与Git Flow模型
  • 日志分析和流量分析
  • typescript基础之关键字type
  • 无人机航测技术有何特点?主要应用在哪些方面?
  • 24届近5年杭州电子科技大学自动化考研院校分析
  • 调整vscode
  • Spring xml 方式整合mybatis 第三方框架
  • RabbitMQ(二) - RabbitMQ与消息发布确认与返回、消费确认
  • 操作指南 | 如何使用Chainlink喂价功能获取价格数据
  • Pandaer的iPhone手机壳
  • 将自己的网站免费发布到互联网上【无需公网IP】
  • 浅谈 Python中if __name__ == ‘__main__‘:的工作原理
  • 【力扣】344. 反转字符串 <首尾指针>
  • Kubectl 详解
  • 华为OD面试记录
  • 电源控制--品质因素Q值全解
  • 实际工作中通过python+go-cqhttp+selenium实现自动检测维护升级并发送QQ通知消息(程序内测)
  • EC200 CAT1 拨号PPP
  • 外网通过ipv6访问家里设备
  • docker 如何使用代理
  • Go和Java实现装饰器模式
  • Android中级——RemoteView
  • SpringBoot核心内容梳理