package javal.util.test;
/**
* 小学生版归并算法
* @author lh
*/
public class ArrayMerge {
/**
* @param arrayA
* @param arrayB
* @return
*/
public static long[] merge(long[] arrayA, long[] arrayB) {
int sizeA = arrayA.length;
int sizeB = arrayB.length;
long[] res = new long[sizeA + sizeB];
int indexA = 0;
int indexB = 0;
int indexRes = 0;
// A B 均未遍历结束
while(indexA < sizeA && indexB < sizeB) {
if(arrayA[indexA] < arrayB[indexB]) {
res[indexRes++] = arrayA[indexA++];
}else {
res[indexRes++] = arrayB[indexB++];
}
}
//A 遍历结束
while(indexB < sizeB) {
res[indexRes++] = arrayB[indexB++];
}
//B 遍历结束
while(indexB < sizeB) {
res[indexRes++] = arrayA[indexA++];
}
return res;
}
public static void main(String[] args) {
long[] a = new long[] {1,3,5,7,9};
long[] b = new long[] {2,4,6,8,10,12};
long[] c = merge(a, b);
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}
}
}
有序数组的归并算法(1)
最新推荐文章于 2021-09-13 13:48:20 发布