JSFiddle - React, Tailwind, and code Playground
by jessekinsman
JavaScript
//from
//https://medium.com/javascript-in-plain-english/common-javascript-algorithms-you-must-know-9ca569ddf46f
/*
Binary Search
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array.
Time Complexity: O(log(n))
*/
function binarySearch(arr, item) {
let startIndex = 0;
let endIndex = arr.length-1;
while (startIndex <= endIndex) {
let middleIndex = Math.floor((startIndex+endIndex)/2);
if (arr[middleIndex] == item) {
return middleIndex;
} else if (middleIndex == endIndex) {
return -1;
}
if (arr[middleIndex] < item) {
startIndex = middleIndex +1;
} else {
endIndex = middleIndex;
}
}
return -1;
}
const searchArr = [5, 10, 20, 30, 40, 50, 60, 80];
searchArr.forEach((item, ind, arr) => {
console.log(`Calling binary search with ${item}`);
let foundIndex = binarySearch(arr, item);
if (foundIndex != ind) {
console.error(`Binary search failed finding index for ${item}\n Should be at index ${ind}.\n Returned ${foundIndex}`);
} else {
console.log(`Found ${item} at index ${foundIndex}`);
}
});
// console.log(binarySearch([5, 10, 20, 30, 40], 30));
//output: Found at index 3