mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
428 字
2 分钟
【算法笔记】(四)归并排序
2026-01-09
统计加载中...

1、用递归的方式实现归并排序#

//递归实现归并排序
public class Main {
public static int[] arr = new int[200];
public static int[] help = new int[200];
public static int n;
public static void main(String[] args) throws IOException {
}
public static void gb (int l ,int r) {
if (l == r) {
return;
}
int m = (l + r) / 2;
gb (l ,m);
gb (m + 1 ,r);
mergeArr (l ,m ,r);
}
private static void mergeArr(int l, int m, int r) {
int left = l ,right = m + 1 ,flag = l;
while (left <= m && right <= r) {
if (arr[left] <= arr[right]) {
help[flag ++] = arr[left ++];
}
else {
help[flag ++] = arr[right ++];
}
}
while (left <= m) help[flag ++] = arr[left ++];
while (right <= r) help[flag ++] = arr[right ++];
for (int i = l ;i <= r ;i ++) {
arr[i] = help[i];
}
}
}

2、用非递归的方式实现归并排序#

package org.example;
import java.io.*;
//非递归实现归并排序
public class Main {
public static int[] arr = new int[200];
public static int[] help = new int[200];
public static int n;
public static void main(String[] args) throws IOException {
}
public static void gb () {
if (n <= 1) return;
for (int l ,r ,mid ,step = 1 ;step < n ;step <<= 1) {
l = 0;
while (l < n) {
mid = l + step - 1;
if (mid + 1 >= n) break;//没有右侧值,直接结束本轮循环
r = Math.min(l + 2 * step - 1 ,n - 1);//注意,右侧的右边界可能长度与左侧相等,也可能长度不够了
mergeArr(l ,mid ,r);
l = r + 1;
}
}
}
private static void mergeArr(int l, int m, int r) {
int left = l ,right = m + 1 ,flag = l;
while (left <= m && right <= r) {
if (arr[left] <= arr[right]) {
help[flag ++] = arr[left ++];
}
else {
help[flag ++] = arr[right ++];
}
}
while (left <= m) help[flag ++] = arr[left ++];
while (right <= r) help[flag ++] = arr[right ++];
for (int i = l ;i <= r ;i ++) {
arr[i] = help[i];
}
}
}
【算法笔记】(四)归并排序
http://hgqwd.icu/posts/suanfa4/
作者
天线宝宝死于谋杀
发布于
2026-01-09
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00