两个有序的数组,合并成一个有序的数组

/**
 * 两个有序的数组,合并成一个有序的数组
 * @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;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值