public static void main(String[] args) {
int[] num1 = new int[]{1, 2, 4, 6, 7, 123, 411, 5334, 1414141, 1314141414};
int[] num2 = new int[]{0, 2, 5, 7, 89, 113, 5623, 6353, 134134};
//變量用于存儲兩個集合應該被比較的索引(存入新集合就加一)
int a = 0;
int b = 0;
int[] num3 = new int[num1.length + num2.length];
for (int i = 0; i < num3.length; i++) {
if (a < num1.length && b < num2.length) { //兩數(shù)組都未遍歷完买雾,相互比較后加入
if (num1[a] > num2[b]) {
num3[i] = num2[b];
b++;
} else {
num3[i] = num1[a];
a++;
}
} else if (a < num1.length) { //num2已經(jīng)遍歷完凝化,無需比較揩徊,直接將剩余num1加入
num3[i] = num1[a];
a++;
} else if (b < num2.length) { //num1已經(jīng)遍歷完似芝,無需比較,直接將剩余num2加入
num3[i] = num2[b];
b++;
}
}
System.out.println( Arrays.toString(num3));
}
方法二:
package com.suanfa.list;
import java.util.ArrayList;
public class shuzupaixu {
public static int[] paixu(int[] a,int[] b) {
//把兩個數(shù)組里的數(shù)據(jù)添加的集合里
ArrayList<Integer> aList = new ArrayList<Integer>(a.length+b.length);
for (int i = 0; i < a.length; i++) {
aList.add(a[i]);
}
for (int j = 0; j < b.length; j++) {
aList.add(b[j]);
}
//把集合再轉(zhuǎn)為數(shù)組
int[] c = new int[aList.size()];
for (int k = 0; k < c.length; k++) {
c[k] = aList.get(k);
}
//冒泡排序得出結(jié)果
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c.length-1-i; j++) {
if (c[j]>c[j+1]) {
int tmp = c[j] ;
c[j] = c[j+1];
c[j+1] = tmp;
}
}
}
return c;
}
public static void main(String[] args) {
int[] a = new int[]{1,20,3};
int[] b = new int[]{4,10,6};
for (int i = 0; i < paixu(a, b).length; i++) {
System.out.print(paixu(a, b)[i]+" ");
}
}
}