Using Scheme to Find the Median of Two Sorted Integer Lists
erichgrunewald.com
erichgrunewald.com
function kth2(a,b,k) {
var ai=0,aj=a.length,bi=0,bj=b.length,d=1;
while (true) {
if (ai==aj) return b[bi+d*k];
if (bi==bj) return a[ai+d*k];
var m=d*(aj-ai),n=d*(bj-bi);
if (k<(m+n)/2) [ai,aj,bi,bj,d,k] = [aj-d,ai-d,bj-d,bi-d,-d,m+n-1-k];
var ak=Math.floor((m+1)/2),bk=Math.floor((n+1)/2);
if (d*a[ai+d*ak-d]<d*b[bi+d*bk-d]) [ai,k] = [ai+d*ak,k-ak];
else [bi,k] = [bi+d*bk,k-bk];
}
}
function median2(a,b) {
var n = a.length+b.length;
if (n%2 == 1) return kth2(a,b,(n-1)/2);
else return (kth2(a,b,n/2-1)+kth2(a,b,n/2))/2;
}The last one is particularly annoying because most problems could be easily tweaked with e.g. restrictions on the size of input or test cases to avoid those issues.
http://pasterack.org/pastes/80529
Note that this solution is using a standard imperative style, with a loop over that narrows down the location of the sought of element in two subvectors of a and b.
You need to do the construction anyways (after all you need the elements of X+Y and you can’t get them without summing)
Given that you have N^2 elements, it would take a total of N^2 log(N) time, which is equivalent in time complexity to simply sorting a list with N^2 elements.
They don’t mean parallel like two thread, though you could use two coroutines or a similar mechanism.
Although in the article the author at some point switches from lists to vectors, which changes the whole task, and allows for a more efficient implementation (even if it's an answer to a different question).
"Getting the median of a single sorted list is trivial: it is either the central value if the list has an odd-numbered length, or the mean of the two central values otherwise."
Is stated with no proof its not something I recall from collage