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.159 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.158 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.157 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.156 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.155 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.154 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.153 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.152 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.151 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.150 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.149 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.148 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.147 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.146 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.145 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.144 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.143 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.142 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.141 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.140 tracks/javascript/exercises/binary-search/example.js