JavaScript Program to Search a Target Value in a Rotated Array
Last Updated :
28 May, 2024
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}}}
// Target not found
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}}
// Target not found
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) {
// Target not found
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));
Method 4: Using Modified Binary Search with Pivot Detection
In this approach, we first find the pivot index of the rotated array. The pivot index is the index where the rotation occurs. Once we have the pivot index, we can perform a modified binary search considering the pivot to determine the target element.
- Find the pivot index:
- We initialize two pointers,
left
and right
, pointing to the start and end of the array, respectively. - While
left
is less than right
, we find the middle element. - If the middle element is greater than the element at the right pointer, it indicates that the pivot lies to the right of the middle element. So, we set
left = mid + 1
. - Otherwise, the pivot lies to the left of the middle element or at the middle element itself. In this case, we set
right = mid
. - After the loop,
left
will be pointing to the pivot index.
- Perform modified binary search:
- Based on the value of the target element and the first element of the array, we determine whether to search in the left half or the right half of the array.
- We perform a binary search considering the pivot index to find the target element.
Example:
JavaScript
const searchInRotatedArray = (nums, target) => {
let left = 0;
let right = nums.length - 1;
// Find the pivot index
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}
const pivot = left;
// Perform modified binary search
left = 0;
right = nums.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const rotatedMid = (mid + pivot) % nums.length;
if (nums[rotatedMid] === target) {
return rotatedMid;
} else if (nums[rotatedMid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
};
const rotatedArray = [5, 6, 7, 8, 9, 10, 1, 2, 3];
const target = 3;
console.log(searchInRotatedArray(rotatedArray, target));
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read