For example, given an integer array and its two consecutive sequence \'s beginning position which are \'b1\' and \'b2\', furthermore provided with the position \'last\' whic
Though it is not possible entirely in O(n) time, I have a proposition to do it faster than O(n^2). I use only O(1) space which is temp in my code. I am sure it should run better than O(n^2).
private static int[] mergeSortedArrays(int[] a1, int[] a2) {
int i = 0, j = 0;
while (a1[i] != Integer.MIN_VALUE) {
if (a1[i] > a2[j]) {
int temp = a1[i];
a1[i] = a2[j];
a2[j] = temp;
for (int k = 1; k < a2.length; k++) {
if (a2[k - 1] > a2[k]) {
temp = a2[k - 1];
a2[k - 1] = a2[k];
a2[k] = temp;
}
}
}
i++;
}
while(j < a2.length){
a1[i++] = a2[j++];
}
return a1;
}