Sha256: b3b9986b35d3c06951c88015ce113cb7cba767774d7c10cc0a11cbd312544ee4

Contents?: true

Size: 721 Bytes

Versions: 181

Compression:

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

181 entries across 181 versions & 1 rubygems

Version Path
trackler-2.1.0.25 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.24 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.23 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.22 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.21 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.20 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.19 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.18 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.17 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.16 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.15 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.14 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.13 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.12 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.11 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.10 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.9 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.8 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.7 tracks/ecmascript/exercises/binary-search/example.js
trackler-2.1.0.6 tracks/ecmascript/exercises/binary-search/example.js