How to use Linear Search In Javascript
In this method, we iterate through the entire array using a loop. During each iteration, we verify if the current element matches the target element. If a match is found, we return the current iteration as the index.
Syntax:
if (arr[index] === targetElement) {
return index;
}
Example: Implementation of the above appraoch.
const searchInRotatedArray =
(inputArray,targetElement) => {
for (let index = 0;index < inputArray.length;index++) {
if (inputArray[index] === targetElement) {
return index}}
// Target not found
return -1;
};
const rotatedArray = [4, 5, 6, 7, 0, 1, 2];
const target = 0;
console.log(searchInRotatedArray(rotatedArray, target));
Output
4
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