Sha256: 935a6b1b36ac2d2d98084a813be3e705c281877f4822b934ab7923d857d75077

Contents?: true

Size: 788 Bytes

Versions: 73

Compression:

Stored size: 788 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

73 entries across 73 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.179 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.178 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.177 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.176 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.175 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.174 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.173 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.172 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.171 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.170 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.169 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.167 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.166 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.165 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.164 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.163 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.162 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.161 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.160 tracks/javascript/exercises/binary-search/example.js