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.119 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.118 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.117 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.116 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.115 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.114 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.113 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.111 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.110 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.109 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.108 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.107 tracks/javascript/exercises/binary-search/example.js
trackler-2.2.1.106 tracks/javascript/exercises/binary-search/example.js