给两个已经排好序的数组。这两个数组的长度可能不相等。怎样将他们合并?
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]);
}
}
}