Sha256: 388c087d14494ef52737b7827e2d162991d9fd690fac9219160c49c38563ba43

Contents?: true

Size: 731 Bytes

Versions: 215

Compression:

Stored size: 731 Bytes

Contents

function isSortedArray(array) {
  for (let i = 1; i < array.length; i++) {
    if (array[i] < array[i - 1]) {
      return false;
    }
  }

  return true;
}

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

  const 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;
}

class BinarySearch {
  constructor(array) {
    if (isSortedArray(array)) {
      this.array = array;
    }
  }

  indexOf(value) {
    return recursiveSearch(this.array, value, 0, this.array.length);
  }
}

export default BinarySearch;

Version data entries

215 entries across 215 versions & 1 rubygems

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