How to use Binary Search In Javascript
In this approach, we begin by locating the middle element of the array. Next, we determine whether the target element is greater or smaller. If it’s greater, we proceed with the second half; otherwise, we focus on the first half.
Syntax:
while (left <= right) {
}
Example: Implementation of the above approach.
const searchInRotatedArray =
(inputArray,targetElement) => {
let left = 0;
let right = inputArray.length - 1;
while (left <= right) {
const mid = Math.floor(
(left + right) / 2);
if (inputArray[mid] === targetElement) {
return mid}
if (inputArray[left] <= inputArray[mid]) {
if (targetElement >= inputArray[left] &&
targetElement < inputArray[mid]) {
right = mid - 1;}
else {
left = mid + 1}}
else {
if (
targetElement > inputArray[mid] &&
targetElement <= inputArray[right]) {
left = mid + 1;}
else {
right = mid - 1}}}
// Target not found
return -1;
};
const rotatedArray = [4, 5, 6, 7, 0, 1, 2,];
const targetElement = 1;
console.log(
searchInRotatedArray(rotatedArray,targetElement));
Output
5
JavaScript Program to Search a Target Value in a Rotated Array
In this article, we are going to implement a JavaScript program to Search for a target value in a rotated array.
Table of Content
- Using Binary Search
- Using Linear Search
- Using Recursive Function
- Using Modified Binary Search with Pivot Detection