In an interview I was asked the following question. I am given two arrays, both of them are sorted.
BUT
Array 1 will have few -1\'s and Array 2 will have to
That's actually an interesting question. There are many sorting algorithms, and the most efficient ones always starts from one "unchangeable" array, so without changing the values inside that. Yet here your goal is to change the value when it encounters -1, so that the value is taken from the second array.
So, you need a sorting algorithm that doesn't divide the array in pieces because if the last element of your second array is 1 (the lowest), it has to be moved to the start. If you're using a sorting algorithm that breaks the array in pieces (the divide-and-conquer tactic like quick sort) or that uses recursion, it can be problematic because it cannot be moved to the start of your main array. Unless you are aware of the main array.
What you need is an algorithm that performs a step-by-step algorithm.
The algorithm that I've used is a bubble sort, which checks each element step by step. It's then easier to replace the value if it's -1 and move its position correctly to the array. However, it is not so efficient. Maybe I will edit my post to see if I can improve that.
function mergeAndSort(arr1, arrMergeIn) {
// merge + sort using arr1 as large one
var mergeIndex = 0;
for (var i = 0; i < arr1.length; ++i) {
if (arr1[i] === -1) arr1[i] = arrMergeIn[mergeIndex++];
var j = i;
while (j > 0 && arr1[j - 1] > arr1[j]) {
var tmp = arr1[j - 1];
arr1[j - 1] = arr1[j];
arr1[j] = tmp;
j--
}
}
return arr1;
}
// one liner console output
function showArray(arr) {
console.log(arr.join(','));
}
showArray(mergeAndSort([3, 6, -1, 11, 15, -1, 23, 34, -1, 42], [7, 19, 38]));
showArray(mergeAndSort([3, 36, -1, 1, 10, -1, 9, 34, -1, 42], [17, 9, 38]));
showArray(mergeAndSort([3, 36, -1, 1, 10, -1, 9, 34, -1, 42], [17, 9, 1]));
showArray(mergeAndSort([-1, 36, -1, 1, 10, -1, 9, 34, -1, 42], [17, 9, 100, 1]));
showArray(mergeAndSort([-1, -1, 1, 100, -1, 9, 34, -1], [17, 9, 9, 1]));
Or, you can use another strategy: replace the "-1" elements with the elements from that another array and perform an efficient algorithm on that. Although in worst-case scenario's, the "-1"s are at the end of the array, which means that there is an ~N operation + additional average complexity of a sorting algorithm (the efficient ones are of ~N*log(N))