合并两个排好序的数组

public static void main(String[] args) {
		
		Integer[] a = {11,23,65,77,98};
		Integer[] b = {22,42,64,72,79};
		Integer[] c = new Integer[a.length+b.length];
		merge(a, b, c);
		System.out.println("\r\n" + "合并排序数组");
		Arrays.asList(c).forEach(e->System.out.print(e + "   "));
	}
	
	/**
	 * 合并俩个排好序的数组
	 * 
	 * @param a
	 * @param b
	 * @param c
	 */
	private static void merge(Integer[] a, Integer[] b, Integer[] c){
		// 判断
		for (int i = 0, j = 0, k = 0 ; i < c.length; i++) {
			if (j == a.length) {
				System.arraycopy(b, k, c, i, c.length-i);
				break;
			}
			if (k == b.length) {
				System.arraycopy(a, j, c, i, c.length-i);
				break;
			}
			if (a[j] <= b[k]) {
				c[i] = a[j++];
			}else {
				c[i] = b[k++];
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/name_javahadoop/article/details/77801343