0

I have a procedure

function m2sa ( A, B )
{
   // finds the media of 2 sorted arrays A and B
   var medIdx = (A.length + B.length)/2;
   var nextSmallest = undefined; 
   for ( var ia  = 0, ib = 0; (ia + ib) < medIdx; )
   {
       if (A[ia] < B[ib]) nextSmallest = A[ia++];
       else nextSmallest = B[ib++];
   }
   return nextSmallest;
}

var sa1 = [1, 5, 39];
var sa2 = [0, 1, 2, 3, 4, 5, 6, 7];
$('#result').text(m2sa(sa1,sa2));

which I'm doing as practice, but I defined I want to make it more rigorous by using the definition of median whereby you average the middle two numbers if the size of the array is even. So I need to change my procedure to

   var medIdx = (A.length + B.length)/2;
   var nextSmallest = undefined; 
   var ia  = 0, ib = 0;
   while ((ia + ib) < medIdx)
   {
       if (A[ia] < B[ib]) nextSmallest = A[ia++];
       else nextSmallest = B[ib++];
   }
   return (medIdx is a whole number) ? (Math.min(A[ia],B[ib]) + nextSmallest)/2 : nextSmallest;

except I'm wondering what I put in place of medIdx is a whole number.

Alternatively, I realize I could do

   var totalLen = A.length + B.length;
   var medIdx = (totalLen)/2;
   var hasVeryMiddle = totalLen % 2 == 1 ? true : false;
   var nextSmallest = undefined; 
   var ia  = 0, ib = 0;
   while ((ia + ib) < medIdx)
   {
       if (A[ia] < B[ib]) nextSmallest = A[ia++];
       else nextSmallest = B[ib++];
   }
   return hasVeryMiddle ? (Math.min(A[ia],B[ib]) + nextSmallest)/2 : nextSmallest;

but that's more code and possible not as efficient as the other procedure.

0 Answers0