The requirement is to start with an empty array, and insert elements into it, one at a time, but keep the array sorted in ascending order. A use of this would be to find the running median of a set of periodic inputs. I have tried simply pushing an element and then invoking the built-in sort method, but appears (by some benchmarks others have done on jsPerf) to slow down with large number of elements.
Duplicates are to be allowed (although a simple trick will let me disallow them as well).
function binaryInsert(x, array) {
var l = 0,
r = array.length - 1,
m;
while (l <= r) {
m = (l + r) / 2 | 0;
if (array[m] > x) {
r = m - 1;
continue;
}
l = m + 1;
if (array[m] === x) {
break; // change to return to avoid duplicates
}
}
array.splice(l, 0, x);
}
I did look at this, but that seems to be doing a recursive search, which does not appear to be optimal without tail call optimization.
Also, are there any alternatives to the splice at the end?