Inserting into a sorted array (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script>
   function getRandom() {
       return Math.floor(Math.random() * 10000);
   }

  var findLocationLogarithmic = function(n, arr) {
                var left = 0;
                var right = arr.length - 1;
                while (left <= right){
                    var mid = Math.floor((left + right) / 2);
                    if (arr[mid] == n)
                        return mid;
                    else if (arr[mid] < n)
                        left = mid + 1;
                    else
                        right = mid - 1;
                }
                return arr.length;
      }
      
      
      
  var findLocationLinear = function(n, arr) {
      var i, len = arr.length;
      for (i = 0; i < len; i++) {
        if (arr[i] >= n) return i;
      }
      return len;
      }
</script>

Setup

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

Teardown


    delete largeArray;
  

Test runner

Ready to run.

Testing in
TestOps/sec
push() and sort()
var newVal = getRandom();
largeArray.push(newVal);
largeArray.sort(function(a, b) {
  return a - b;
});
ready
splice() with logarithmic search
var newVal = getRandom();
var newPos = findLocationLogarithmic(newVal, largeArray);
largeArray.splice(newPos, 0, newVal);
ready
splice() with linear search
var newVal = getRandom();
var newPos = findLocationLinear(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.