Sha256: bae7dc8dcac331cb2a94514c1b06d4043bd100b39811643377a8ec527e5edd34

Contents?: true

Size: 783 Bytes

Versions: 255

Compression:

Stored size: 783 Bytes

Contents

'use strict';

function BinarySearch(array) {

  //check if array is sorted
  var arrayIsSorted = true;
  for (var i = 1; i < array.length; i++) {
    if (array[i] < array[i - 1]) arrayIsSorted = false;
  }

  //instantiate the array if sorted
  if (arrayIsSorted) this.array = array;

  //use binary search for indexOf
  this.indexOf = function(value) {
    return recursiveSearch(this.array, value, 0, this.array.length);
  };
}


function recursiveSearch(array, value, start, end) {
  if (start == end) return -1;

  var mid = Math.floor((start + end) / 2);

  if (array[mid] > value) {
    return recursiveSearch(array, value, start, mid);
  }
  if (array[mid] < value) {
    return recursiveSearch(array, value, mid + 1, end);
  }
  return mid;
}

module.exports = BinarySearch;

Version data entries

255 entries across 255 versions & 1 rubygems

Version Path
trackler-2.1.0.40 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.39 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.38 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.37 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.36 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.34 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.33 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.32 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.31 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.30 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.29 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.28 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.27 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.26 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.25 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.24 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.23 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.22 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.21 tracks/javascript/exercises/binary-search/example.js
trackler-2.1.0.20 tracks/javascript/exercises/binary-search/example.js