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.139 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.138 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.137 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.136 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.135 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.134 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.133 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.132 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.131 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.130 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.129 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.128 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.127 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.126 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.125 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.124 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.123 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.122 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.121 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.120 tracks/javascript/exercises/binary-search/example.js