将一个二维数组直接拆分成一维数组:
多路归并算法
将二维数组视为k个一维数组,每次取k个数组里面第一个最小的,然后从其中k(有可能小于k)个数选择最小的,并将指向最小元素的那个数据段指针后移
直到k个数组都遍历完毕。
暴力解法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24public class Main{ public static void main(String[] args) { int[][] m = { { 1, 23 }, { 2, 3, 4, 5 } }; int[] n; int len = 0; // 计算一维数组长度 for (int[] element : m) { len += element.length; } // 复制元素 n = new int[len]; int index = 0; for (int[] element : m) { for (int element2 : element) { n[index++] = element2; } } Arrays.sort(n); for (int i : n) { System.out.print(i + ",");//输出所有的数据 } } }
多路归并:
合并两个有序数组
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public class Dahua{ public static void main(String[] args) { public class SortTwoArray { public int[] sort(int[] a,int[] b){ int[] c = new int[a.length+b.length]; int i=0,j=0,k = 0; while (i<a.length&&j<b.length){ if(a[i]>=b[j]){ c[k++] = b[j++]; }else { c[k++] = a[i++]; } } while (j<b.length){ c[k++] = b[j++]; } while (i<a.length){ c[k++] = a[i++]; } return c; } } } }
多个数组怎么合并?
当输入是一个List<int[]>时,
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * */ public class test { public static void main(String[] args) { int[] aa = { 1, 3, 13, 9}; int[] bb = { 5, 4, 7, 18}; int[] cc = { 7, 5, 8, 11}; List<int[]> arr = new ArrayList<>(); arr.add(aa); arr.add(bb); arr.add(cc); //输出查看是否将数组加进去 for (int[] ints : arr) { System.out.println(); for (int anInt : ints) { System.out.print(anInt + " "); } } System.out.println(); System.out.println("结果是:"); int[] aa0 = null; //两两将数组进行合并 for (int i = 0; i < arr.size(); i++) { int[] aa1 = arr.get(i); int[] newInt = merge(aa0,aa1); aa0 = newInt; } Arrays.sort(aa0); for (int i : aa0) { System.out.print(i + " "); } } public static int[] merge(int[] a,int[] b){ if (a == null) { return b; } int[] c = new int[a.length+b.length]; int i=0,j=0,k = 0; while (i<a.length&&j<b.length){ if(a[i]>=b[j]){ c[k++] = b[j++]; }else { c[k++] = a[i++]; } } while (j<b.length){ c[k++] = b[j++]; } while (i<a.length){ c[k++] = a[i++]; } return c; } }
最后
以上就是大意大叔最近收集整理的关于【归并法排序 】采用二维数组直接拆分一维数组暴力解法多路归并:多个数组怎么合并?的全部内容,更多相关【归并法排序内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复