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.

Input

Array: [4, 5, 6, 1, 2, 3]

Output

Pivot index: 2

Note that the pivot index can vary depending on the input array.

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);

Performing Binary Search

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. We will need two separate binary search functions: one for the first sub-array and one for the second sub-array.

Input − const arr = [1, 2, 3, 4, 5, 6, 7]; const key = 4;

Output  3

In this example, the binary search function returns the index '3', which corresponds to the value '4' in the array.

Example: Binary search function

The program below searches for a key in an array using the binary search algorithm. It first checks if the key is present in the array by comparing the starting and ending indices. If the key is not present, it returns -1. If it is present, it calculates the mid index and compares the value at that index with the key. If the value is equal to the key, it returns the mid-index. If the value is less than the key, it continues searching in the right half of the array, and if it is greater than the key, it searches in the left half of the array, until the key is found or not present in the array.

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);
   }
}
const arr = [1, 2, 3, 4, 5, 6, 7];
const key = 4;
const result = binarySearch(arr, 0, arr.length - 1, key);
console.log("The searched element found at index ", result);

Conclusion

Searching for an element in a sorted and rotated array can be achieved using a modified binary search algorithm. The key to this algorithm is identifying the pivot point in the array and then dividing the array into two sorted subarrays. The binary search is then performed on the appropriate subarray to locate the key. The implementation of this algorithm in JavaScript requires careful consideration of edge cases and implementation details, but the result is a fast and efficient search function that can handle sorted and rotated arrays of any size.

Updated on: 20-Apr-2023

222 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements