浏览脉脉的时候,有个匿名帖子,据说是去面试,人家给出的算法题:
合并两个有序数组,如代码所示那种,合并以后保持有序。
趁着午间休息,写了一下:
public static void testMergeSequentialArray() {
int[] b1 = {1, 3, 9, 11};
int[] b2 = {2, 3, 8, 10, 12};
int n1 = 0;
int n2 = 0;
int nFinal = 0;
int[] finalArr = new int[b1.length + b2.length];
while (nFinal < finalArr.length) {
int temp2 = n2 < b2.length ? b2[n2] : -1;
int temp1 = n1 < b1.length ? b1[n1] : temp2;
if (temp1 < temp2) {
finalArr[nFinal] = temp1;
n1++;
} else {
finalArr[nFinal] = temp2;
n2++;
}
nFinal++;
Log.i(TAG, "nFinal is " + nFinal + " ..n1 is " + n1 + " ..n2 is " + n2);
printArray(finalArr);
}
}
public static void printArray(int[] a){
StringBuffer s = new StringBuffer();
for (int i = 0; i < a.length; i++) {
s.append(a[i]).append(" ");
}
Log.i(TAG, "finalArr=" + s);
}