How can I compare two sets of 1000 numbers against each other? How can I compare two sets of 1000 numbers against each other? sql sql

How can I compare two sets of 1000 numbers against each other?


Sort the lists first. Then you can walk up both lists from the start, comparing as you go.

The loop would look something like this:

var A = getFirstArray().sort(), B = getSecondArray().sort();var i = 0, j = 0;while (i < A.length && j < B.length) {    if (A[i] === B[j]) {        doBla(A[i]);        i++; j++;    }    else if (A[i] < B[j]) {        i++;    }    else        j++;}

(That's JavaScript; you could do it server-side too, but I don't know PHP.)

Edit — just to be fair to all the hashtable fans (whom I respect of course), it's pretty easy to do that in JavaScript:

var map = {};for (var i = 0; i < B.length; ++i) map[B[i]] = true; // Assume integers.for (var i = 0; i < A.length; ++i) if (map[A[i]]) doBla(A[i]);

Or if the numbers are or might be floats:

var map = {};for (var i = 0; i < B.length; ++i) map['' + B[i]] = true; // Assume integers.for (var i = 0; i < A.length; ++i) if (map['' + A[i]]) doBla(A[i]);

Since numbers are pretty cheap to hash (even in JavaScript, converting to string before hashing is surprisingly cheap), this would be pretty fast.


In database terms this can a join of 1000 rows to another 1000 rows. Any modern database system can handle this.

select x from table1inner join table2on table1.x = table2.y

where table1 and table2 are the rows concerned and could be the same table.