Inserting into a sorted array

Benchmark created on


Preparation HTML

<script>
  var findLocationFor = function(n, arr) {
      var i = Math.floor(arr.length / 2);
      var prev_i = arr.length;
      while (1) {
        var b = i;
        if (arr[i] === n) return i + 1;
        if (arr[i] < n) {
          if (i === arr.length - 1 || arr[i + 1] > n) {
            return i + 1;
          }
  
          i += Math.floor(Math.abs(prev_i - i) / 2);
        } else // arr[i] > n
        {
          if (i === 0 || arr[i - 1] < n) {
            return i + 1;
          }
  
          i -= Math.floor(Math.abs(prev_i - i) / 2);
        }
        prev_i = b;
      }
      }
</script>

Setup

var largeArray = [];
    for (var n = 0; n < 10000; n++) {
      largeArray.push(n);
    }
    
    var newVal = 1337.5;

Teardown


    delete largeArray;
  

Test runner

Ready to run.

Testing in
TestOps/sec
push() and sort()
largeArray.push(newVal);
largeArray.sort(function(a, b) {
  return a - b;
});
ready
splice()
var newPos = findLocationFor(newVal, largeArray);
largeArray.splice(newPos, 0, newVal);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.