JavaScript Program for Search an element in a sorted and rotated array

When an array is sorted in ascending order and then rotated by some pivot point, it becomes challenging to search for an element using traditional search algorithms. As a developer, you need to find an efficient solution to this problem.

In this article, we will guide you through the process of writing a JavaScript program to search for an element in a sorted and rotated array. We will explain the underlying logic and provide you with a step-by-step approach to implementing this program.

Problem Statement

Before we begin, let's understand the problem statement. We have a sorted array that has been rotated by some unknown amount.

For example, the original array could be [1, 2, 3, 4, 5, 6], but after rotation, it becomes [4, 5, 6, 1, 2, 3]. Now, we need to search for a specific element in the rotated array.

The first thing we need to do is find the pivot point, which is the point at which the array was rotated. Once we have found the pivot point, we can perform a binary search on the two sub-arrays to find the element we are looking for.

Finding the Pivot Point

To find the pivot point, we can use a modified binary search algorithm. We start by finding the middle element of the array and comparing it with the first element. If the middle element is greater than the first element, we know that the pivot point is in the second half of the array. If the middle element is less than the first element, we know that the pivot point is in the first half of the array.

We continue this process until we find the pivot point. Once we have found the pivot point, we can split the array into two sub-arrays and perform a binary search on both of them.

Example: Finding the Pivot Point

In the below JavaScript program, we have an array [4, 5, 6, 1, 2, 3] which is sorted and rotated. We call the 'findPivot function' with the array, starting index '0', and ending index 'arr.length - 1'. The function returns the index of the pivot point, which is '2' in this case.

function findPivot(arr, low, high) {
   if (high < low) return -1;
   if (high === low) return low;
   
   const mid = Math.floor((low + high) / 2);
   
   if (mid < high && arr[mid] > arr[mid + 1]) {
      return mid;
   }
   if (mid > low && arr[mid] < arr[mid - 1]) {
      return mid - 1;
   }
   if (arr[low] >= arr[mid]) {
      return findPivot(arr, low, mid - 1);
   }
   return findPivot(arr, mid + 1, high);
}

// Example usage
const arr = [4, 5, 6, 1, 2, 3];
console.log("Array:", JSON.stringify(arr));
const pivotIndex = findPivot(arr, 0, arr.length - 1);
console.log("Pivot index:", pivotIndex);
Array: [4,5,6,1,2,3]
Pivot index: 2

Binary Search Function

Once we have found the pivot point, we can perform a binary search on both sub-arrays to find the element we are looking for. The program below searches for a key in an array using the binary search algorithm.

function binarySearch(arr, low, high, key) {
   if (high < low) return -1;
   
   const mid = Math.floor((low + high) / 2);
   
   if (arr[mid] === key) {
      return mid;
   } else if (key < arr[mid]) {
      return binarySearch(arr, low, mid - 1, key);
   } else {
      return binarySearch(arr, mid + 1, high, key);
   }
}

// Example: Search in a regular sorted array
const sortedArr = [1, 2, 3, 4, 5, 6, 7];
const key = 4;
const result = binarySearch(sortedArr, 0, sortedArr.length - 1, key);
console.log("Element", key, "found at index:", result);
Element 4 found at index: 3

Complete Solution: Search in Rotated Array

Now let's combine both functions to create a complete solution that searches for an element in a sorted and rotated array:

function findPivot(arr, low, high) {
   if (high < low) return -1;
   if (high === low) return low;
   
   const mid = Math.floor((low + high) / 2);
   
   if (mid < high && arr[mid] > arr[mid + 1]) {
      return mid;
   }
   if (mid > low && arr[mid] < arr[mid - 1]) {
      return mid - 1;
   }
   if (arr[low] >= arr[mid]) {
      return findPivot(arr, low, mid - 1);
   }
   return findPivot(arr, mid + 1, high);
}

function binarySearch(arr, low, high, key) {
   if (high < low) return -1;
   
   const mid = Math.floor((low + high) / 2);
   
   if (arr[mid] === key) {
      return mid;
   } else if (key < arr[mid]) {
      return binarySearch(arr, low, mid - 1, key);
   } else {
      return binarySearch(arr, mid + 1, high, key);
   }
}

function searchInRotatedArray(arr, key) {
   const n = arr.length;
   const pivot = findPivot(arr, 0, n - 1);
   
   // If no pivot found, array is not rotated
   if (pivot === -1) {
      return binarySearch(arr, 0, n - 1, key);
   }
   
   // If key is at pivot
   if (arr[pivot] === key) {
      return pivot;
   }
   
   // Search in first half
   if (arr[0] <= key) {
      return binarySearch(arr, 0, pivot - 1, key);
   }
   
   // Search in second half
   return binarySearch(arr, pivot + 1, n - 1, key);
}

// Example usage
const rotatedArr = [4, 5, 6, 1, 2, 3];
const searchKey = 2;

console.log("Array:", JSON.stringify(rotatedArr));
console.log("Searching for:", searchKey);

const index = searchInRotatedArray(rotatedArr, searchKey);
if (index !== -1) {
   console.log("Element found at index:", index);
} else {
   console.log("Element not found");
}
Array: [4,5,6,1,2,3]
Searching for: 2
Element found at index: 4

Time and Space Complexity

Operation Time Complexity Space Complexity
Finding Pivot O(log n) O(log n)
Binary Search O(log n) O(log n)
Overall Solution O(log n) O(log n)

Conclusion

Searching for an element in a sorted and rotated array can be efficiently achieved using a modified binary search algorithm. The key is identifying the pivot point and then performing binary search on the appropriate subarray, maintaining O(log n) time complexity.

Updated on: 2026-03-15T23:19:01+05:30

438 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements