I am working on a problem in Javascript. Finding common minimum value between two arrays. However, I have been told that this might not work on some values. What is the issue?
function cmp(a, b) { return a - b; }
function findMinimum(A, B) {
var n = A.length;
var m = B.length;
A.sort(cmp);
B.sort(cmp);
var i = 0;
for (var k = 0; k < n; k++) {
if (i < m - 1 && B[i] < A[k])
i += 1;
if (A[k] == B[i])
return A[k];
}
return -1;
}
Let's take,
and run through your loop.
Your script fails.
The correct logic should be, you either increment
i
ork
in 1 iteration. Not bothI would do something like,
This should work. Just replace the first
if
with awhile
. Thewhile
loop loops through array B till it finds an element which is greater than the minimum element of A. Then the outerfor
loop loops through A to find any element that matches the current element of B or till it reaches an element that is greater than the current element of B, where the process repeats.I'd suggest changing your methodology here. Sorting both of the arrays at the beginning is expensive. Find the intersection set of two arrays and then sort it and return its mimimum value, that's all.