当前位置:网站首页>堆排序 和冒泡排序
堆排序 和冒泡排序
2022-08-11 04:00:00 【mmmenxj】
1.堆排序是nlogN级别的排序:
public static void heapSort(int[] arr){
//1.先将arr进行heapify调整为最大堆
//从最后一个非叶子结点开始进行shiftDown操作
for (int i = (arr.length -1 -1)>>1; i >= 0; i--) {
shiftDown(arr, i, arr.length);
}
//此时arr调整为最大堆
for (int i = arr.length -1; i >0 ; i--) {
//arr[0]就是堆顶元素,就是当前堆的最大值
swap(arr,0,i);
shiftDown(arr,0,i);
}
}
//元素下沉操作
private static void shiftDown(int[] arr, int i, int length) {
while(2* i +1 <length){
int j = (i<<1) +1;
if(j + 1<length && arr[j +1] >arr[j]){
j = j+1;
}
//j就是左右子树的最大值
if(arr[i] >arr[j]){
//下沉结束
break;
}else{
swap(arr,i,j);
i = j;
}
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = {7,5,4,3,1,2,10,9,8};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}2.冒泡排序o(n^2)
public static void bubbleSort(int[] arr){
for (int i = 0; i <arr.length -1; i++) {
boolean isSwaped = false;
for (int j = 0; j <arr.length -1 -i; j++) {
if(arr[j] >arr[j +1]){
swap(arr,j,j+1);
isSwaped = true;
}
}
if(!isSwaped){
break;//已经彻底有序了
}
}堆和优先级队列:
1.最大堆、最小堆实现
2.堆排序
3.TopK问题
17.14 -- 343--373
边栏推荐
- js uses the string as the js execution code
- MYSQLg高级------回表
- What are port 80 and port 443?What's the difference?
- 洛谷P5139 z小f的函数
- App基本框架搭建丨日志管理 - KLog
- CTO said that the number of rows in a MySQL table should not exceed 2000w, why?
- The "top pillar" slides, and new growth is extremely difficult to shoulder the heavy responsibility. Is Ali "squatting" to jump higher?
- Power Cabinet Data Monitoring RTU
- Common layout effect realization scheme
- DNS separation resolution and intelligent resolution
猜你喜欢

校园兼职平台项目反思

What is Machine Reinforcement Learning?What is the principle?

Multi-serial port RS485 industrial gateway BL110

【FPGA】day22-SPI协议回环

Detailed explanation of VIT source code

【FPGA】day21- moving average filter

LeetCode814算题第15天二叉树系列值《814 二叉树剪枝》

这些云自动化测试工具值得拥有

Kubernetes集群搭建Zabbix监控平台

Interchangeability and Measurement Technology—Surface Roughness Selection and Marking Method
随机推荐
【FPGA】设计思路——I2C协议
leetCode刷题14天二叉树系列之《 110 平衡二叉树判断》
Detailed explanation of VIT source code
"125 Palindrome Verification" of the 10th day string series of LeetCode brushing questions
What is machine learning?Explain machine learning concepts in detail
Watch to monitor
洛谷P1763 埃及分数
【FPGA】day21-移动平均滤波器
什么是机器强化学习?原理是什么?
AVH 动手实践 (二) | 在 Arm 虚拟硬件上部署 PP-OCR 模型
洛谷P2370 yyy2015c01 的 U 盘
使用百度EasyDL实现森林火灾预警识别
"3 Longest Substring Without Repeating Characters" on the 17th day of LeetCode brushing
.NET自定义中间件
【FPGA】day21- moving average filter
Is there any way for kingbaseES to not read the system view under sys_catalog by default?
What is Machine Reinforcement Learning?What is the principle?
Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
Leetcode 669. 修剪二叉搜索树
【C语言】入门