Last active
March 31, 2022 16:56
-
-
Save tesmen/ea520685eca1a9d387a5c37e25e321b0 to your computer and use it in GitHub Desktop.
Simple binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable */ | |
class VelocityChecker { | |
arrayData = [] | |
iterationsCount = 0 | |
from | |
to | |
constructor(from, to) { | |
this.from = from | |
this.to = to | |
this.fillArrayData() | |
} | |
/** | |
* @param {number[]} targets | |
*/ | |
runTestArray(targets) { | |
targets.map(target => this.runTest(target)) | |
} | |
/** | |
* @private | |
*/ | |
reset() { | |
this.iterationsCount = 0 | |
} | |
runTest(value) { | |
this.reset() | |
console.log(`>>> Looking for ${value}`) | |
this.targetValue = value | |
this.findOneSilly(this.targetValue) | |
this.findOneBinary(this.targetValue) | |
} | |
/** | |
* @private | |
*/ | |
fillArrayData() { | |
console.time('fillArrayData') | |
for(let i = this.from; i <= this.to; i++) { | |
this.arrayData.push(i) | |
} | |
console.timeEnd('fillArrayData') | |
} | |
/** | |
* @private | |
*/ | |
findOneSilly(val) { | |
console.time('findOneSilly') | |
this.arrayData.indexOf(val) | |
console.timeEnd('findOneSilly') | |
} | |
/** | |
* @private | |
*/ | |
findOneBinary(val) { | |
console.time('findOneBinary') | |
const index = this.binarySearch(val, 0, this.arrayData.length - 1) | |
console.timeEnd('findOneBinary') | |
if(index !== null) { | |
console.log(`iterations: ${this.iterationsCount} found at index ${index}`) | |
return index | |
} | |
console.error(`Not found after ${this.iterationsCount} iterations`) | |
} | |
/** | |
* @private | |
* @param {number} targetValue | |
* @param {number} startIndex | |
* @param {number} endIndex | |
* @return {number|*|null} | |
*/ | |
binarySearch(targetValue, startIndex, endIndex) { | |
this.iterationsCount++ | |
const middle = Math.floor((startIndex + endIndex) / 2) | |
// console.log(`looking for ${targetValue}`, `from ${startIndex} -`, endIndex, `with middle at ${middle}`) | |
if(startIndex > endIndex) { | |
return null | |
} | |
if(this.arrayData[middle] === targetValue) { | |
return middle | |
} | |
return this.arrayData[middle] > targetValue | |
? this.binarySearch(targetValue, startIndex, middle - 1) | |
: this.binarySearch(targetValue, middle + 1, endIndex) | |
} | |
} | |
const testSet = { | |
range: { min: 0, max: 1e+8 }, | |
targets: [ -1, 0, 5e+7, 1e+8, 1e+8 + 1 ], | |
} | |
const instance = new VelocityChecker(testSet.range.min, testSet.range.max) | |
instance.runTestArray(testSet.targets) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment