给两个已经排好序的数组,这两个数组的长度可能不相等,如何将他们合并?
package airth; public class TestMergeArray { /** * 功能: * 作者: jiangfuqiang * 创建日期:2014-10-13 * 修改者: mender * 修改日期: modifydate * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] a = {1,3,5,7}; int[] b = {0,4,8}; int[] c = new int[a.length + b.length]; int index = 0; int count = 0; int times = 0; for (int i = 0; i < b.length; i++) { for(int j = count; j < a.length; j++) { if(b[i] < a[j]) { c[index++] = b[i]; times++; break; } else { count++; c[index++] = a[j]; } } } //判断如果短数组中还有未被利用的数据,则加入新数组的最后面 while(times < b.length) { c[index++] = b[times++]; } for(int i = 0; i< c.length; i++) { System.out.println(c[i]); } } }
时间: 2024-10-23 06:27:17