EDIT: code snippet added, check the output in JS console
I wrote the following binary search algorithm in JS, for the first time in my experience. The variable sampleObj
is a random object array in the form of: [{index: 5, sample: 3}, {index: 8, sample: 1}, ...]
, the final console.log(sampleObj)
should log target value and index in an object if found, 'not found'
if not found
My idea is:
- sort the sample object array from small to large value, along with the index of each value,
- find the middle value of the array, if it equals to
target
, return the object; if it's larger, assign the first half of the object array tosampleObj
, otherwise assign the second half, - repeat until found or not found.
The code consists of 3 main parts:
- generate sample object array,
- define binary search method,
- conduct a binary search.
Here is the code, it passed all my test cases, but what can I improve?
// sample size
const N = 20;
const sample = Array.from({length: N}, () => Math.floor(Math.random() * N));
// define target value
const target = 0;
const indices = [...Array(N).keys()];
const sampleWithIndices = [sample, indices];
let sampleObj;
console.log(sampleWithIndices);
console.log(`target is ${target}`);
// 1. generate sample object array
const generateObj = (origin) => {
let output = [];
for(let i = 0; i < origin.length; i++) {
let index = [...Array(N).keys()];
output[i] = {
'sample': origin[i],
'index': index[i]
}
}
return output;
};
sampleObj = generateObj(sample);
// sort sample object by sample array
const sortSampleObj = (input) => {
return input.sort((a, b) => {
return a.sample - b.sample
})
};
sampleObj = sortSampleObj(sampleObj);
// 2. define binary search method
const binarySearch = (inputObj, inputMidIndex, inputMidSampleValue, inputTarget) => {
if(inputMidSampleValue === inputTarget) {
inputObj = [inputObj[inputMidIndex]];
}
else if(inputMidSampleValue > inputTarget) {
inputObj = inputObj.slice(0, inputMidIndex);
}
else {
inputObj = inputObj.slice(inputMidIndex);
}
return inputObj;
};
// 3. conduct binary search
let midIndex, midSampleValue, maxIterations;
maxIterations = Math.round(sampleObj.length / 2);
for(let i = 0; i < maxIterations; i++) {
midIndex = Math.round(sampleObj.length / 2) - 1;
midSampleValue = sampleObj[midIndex].sample;
sampleObj = binarySearch(sampleObj, midIndex, midSampleValue, target);
if (sampleObj.length === 1) {
sampleObj = sampleObj[0].sample === target ? sampleObj : 'not found';
break;
}
}
console.log(sampleObj)