归并排序_JAVA
2024-09-17 05:28:57
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = { 6, -2, 7, 8, 3, 4, 12, 1, 0, -3, -8, 3, 4, 7 };
System.out.println("排序之前:" + Arrays.toString(a));
sort(a, 0, a.length - 1);
System.out.println("排序之后:" + Arrays.toString(a));
}
public static int[] sort(int[] a, int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
sort(a, low, mid);
sort(a, mid + 1, high);
merge(a, low, mid, high);
}
return a;
}
public static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
// 将两数组中较小的放入temp
while (i <= mid && j <= high) {
if (a[i] < a[j]) {
temp[k] = a[i];
k++;
i++;
} else {
temp[k] = a[j];
k++;
j++;
}
}
// 将剩余的放入temp
while (i <= mid) {
temp[k] = a[i];
k++;
i++;
}
while (j <= high) {
temp[k] = a[j];
k++;
j++;
}
// 用temp覆盖a
for (int k2 = 0; k2 < temp.length; k2++) {
a[k2 + low] = temp[k2];
}
}
}
最新文章
- [No000039]操作系统Operating Systems用户级线程User Threads
- 分享Kali Linux 2016.2第42周镜像文件
- Tomcat 常用配置
- PostgreSQL Replication之第十二章 与Postgres-XC一起工作(3)
- 动态树LCT小结
- NET基础课--代码安全
- java jquery 函数多參数传递
- [帖子收集]环境光遮蔽(Ambient Occlusion)
- ~.NET下国际化i18n简单示例
- 【二分贪心】Bzoj3969 [WF2013] Low Power
- 并发容器学习—ConcurrentSkipListMap与ConcurrentSkipListSet 原
- python学习第天14天。
- XamarinAndroid组件教程RecylerView动画组件使用动画(3)
- 抖音爆火的随机点名Java实现原理,没有连接数据库
- jQuery笔记-插件开发小技巧
- Qt_QString::split测试
- jenkins坑—— shell 命令返回空导致构建失败
- [leetcode tree]98. Validate Binary Search Tree
- bzoj1618 / P2918 [USACO08NOV]买干草Buying Hay(完全背包)
- 32位C#程序连接64位ORACLE数据库
热门文章
- 诶西,JavaScript学习记录。。。。。。
- [2017-7-28]Android Learning Day7
- 洛谷 P4705 玩游戏 解题报告
- 【php】php分隔字符串为数组
- Nginx宣布正式支持gRPC,附示例代码
- poj3349 Snowflake Snow Snowflakes
- [luogu3294][背单词]
- SetCapture() &; ReleaseCapture() 捕获窗口外的【松开左键事件】: WM_LBUTTONUP
- Keyboard Hook API函数 参数说明
- linux:提取匹配含有小数点的数字(grep函数)