/**
* 两个有序的数组,合并成一个有序的数组
* @author ccq
*
*/
public class Test1 {
public static void main(String[] args) {
int[] a = new int[] { 1, 3, 5, 7, 8, 8, 9, 100, 111, 222 };
int[] b = new int[] { 2, 3, 4, 5, 6, 7, 8 };
int arr[] = sortArr(a, b);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
/**
* 算法复杂度O(m+n)
* m : a数组的长度
* n : b数组的长度
* @param a
* @param b
* @return arr 合并后的数组
*/
public static int[] sortArr(int[] a, int[] b) {
int sum = 0;
int aIndex = 0;
int bIndex = 0;
int arrIndex = 0;
int aLen = a.length;
int bLen = b.length;
int[] arr = new int[aLen + bLen];
while (aIndex < aLen && bIndex < bLen) {
if (a[aIndex] < b[bIndex]) {
arr[arrIndex++] = a[aIndex++];
}else if(a[aIndex] == b[bIndex]){
arr[arrIndex++] = a[aIndex++];
arr[arrIndex++] = b[bIndex++];
}else {
arr[arrIndex++] = b[bIndex++];
}
sum++;
}
for (int i = aIndex; i < aLen; i++) {
arr[arrIndex++] = a[i];
sum++;
}
for (int i = bIndex; i < bLen; i++) {
arr[arrIndex++] = b[i];
sum++;
}
System.out.println("sum = " + sum + ", a+b = " + (aLen + bLen));
return arr;
}
}
两个有序的数组,合并成一个有序的数组
最新推荐文章于 2021-10-19 17:46:47 发布
本文介绍了一种将两个已排序的整数数组合并为一个有序数组的方法。该算法的时间复杂度为O(m+n),其中m和n分别为两个输入数组的长度。通过逐个比较两个数组中的元素并选择较小者加入新数组,最终实现合并。
3572

被折叠的 条评论
为什么被折叠?



