基础算法(一) ———— 合并两个有序数组

题目:合并两个有序数组. 

实现思想:为了考虑算法实现的效率,采用数组从后往前合并,先计算出合并后的数组的长度,再设置一个索引从数组的末尾往前赋值。


具体实现:

<span style="font-family:Microsoft YaHei;font-size:18px;">package com.demo.combiner;

public class Combine {
	public static void combine(int[] a1, int[] a2) {
		if (a1 == null || a2 == null || (a1.length + a2.length) > 1024) {
			return;
		}
		int length1 = a1.length - 1;	//数组1的索引
		int length2 = a2.length - 1;	//数组2的索引
		int length = length1 + length2 + 2;		//新数组的长度
		int len = length - 1;	//新数组的索引
		int[] array = new int[length];
		//循环数组1和数组2中的值
		while (length1 >= 0 && length2 >= 0) {
			//对数组1和数组2中的值进行比较
			if (a1[length1] >= a2[length2]) {
				//数组1中的大就将数组1中的值存至新数组
				array[len--] = a1[length1--];
			} else {
				//数组2中的大就将数组1中的值存至新数组
				array[len--] = a2[length2--];
			}
		}

		while (length1 >= 0) {
			array[len--] = a1[length1--];
		}

		while (length2 >= 0) {
			array[len--] = a1[length2--];
		}
		for (int i=0; i<array.length;i++) {
			System.out.print(array[i] + "  ");
		}
		System.out.println();
		return;
	}

	public static void main(String[] args) {
		int[] a1 = new int[] { 1, 3, 4, 5 };
		int[] a2 = new int[] { 2, 4, 6, 10 };
		combine(a1, a2);
	}
}
</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值