我有一个程序
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));
我做的是练习,但我定义我想通过使用中位数的定义使其更加严格,如果数组的大小是,则平均中间的两个数字甚至。所以我需要将我的程序改为
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;
除了我想知道我代替medIdx is a whole number
。
或者,我意识到我可以做到
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;
但是代码更多,可能效率不如其他程序。