JavaScript Program to Search a Target Value in a Rotated Array
Last Updated :
07 Nov, 2023
In this article, we are going to implement a JavaScript program to Search for a target value in a rotated array.
Using Binary Search
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.
Javascript
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}}}
return -1;
};
const rotatedArray = [4, 5, 6, 7, 0, 1, 2,];
const targetElement = 1;
console.log(
searchInRotatedArray(rotatedArray,targetElement));
|
Using Linear Search
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.
Javascript
const searchInRotatedArray =
(inputArray,targetElement) => {
for (let index = 0;index < inputArray.length;index++) {
if (inputArray[index] === targetElement) {
return index}}
return -1;
};
const rotatedArray = [4, 5, 6, 7, 0, 1, 2];
const target = 0;
console.log(searchInRotatedArray(rotatedArray, target));
|
Using Recursive Function
In this method, similar to binary search, we divide the array into two halves: the left half and the right half. We then apply a recursive binary search within these halves.
Syntax:
return searchInRotatedArray( nums, target, left, mid - 1)
Example: Implementation of the above approach.
Javascript
const searchInRotatedArray =
( nums, target, left = 0, right = nums.length - 1) => {
if (left > right) {
return -1}
const mid = Math.floor(
(left + right) / 2);
if (nums[mid] === target) {
return mid}
if (nums[left] <= nums[mid]) {
if (target >= nums[left] &&
target < nums[mid]) {
return searchInRotatedArray(
nums , target , left , mid - 1 )}
else {
return searchInRotatedArray(
nums, target, mid + 1, right)}}
else {
if (target > nums[mid] && target <= nums[right]) {
return searchInRotatedArray(
nums, target, mid + 1, right)}
else {
return searchInRotatedArray(
nums, target, left, mid - 1)}}};
const rotatedArray = [5, 6, 7, 8, 9, 10, 1, 2, 3];
const target = 3;
console.log(searchInRotatedArray(rotatedArray,target));
|
Share your thoughts in the comments
Please Login to comment...