Javascript Program for Search an element in a sorted and rotated array
Last Updated :
19 Sep, 2023
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.
Example:
Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
key = 3
Output : Found at index 8
Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
key = 30
Output : Not found
Input : arr[] = {30, 40, 50, 10, 20}
key = 10
Output : Found at index 3
All solutions provided here assume that all elements in the array are distinct.
Basic Solution:
Approach:
- The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.
- The main idea for finding pivot is - for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.
- Using the above statement and binary search pivot can be found.
- After the pivot is found out divide the array in two sub-arrays.
- Now the individual sub - arrays are sorted so the element can be searched using Binary Search.
Implementation:
Input arr[] = {3, 4, 5, 1, 2}
Element to Search = 1
1) Find out pivot point and divide the array in two
sub-arrays. (pivot = 2) /*Index of 5*/
2) Now call binary search for one of the two sub-arrays.
(a) If element is greater than 0th element then
search in left array
(b) Else Search in right array
(1 will go in else as 1 < 0th element(3))
3) If element is found in selected sub-array then return index
Else return -1.
Below is the implementation of the above approach:
JavaScript
<script>
/* JavaScript Program to search an element
in a sorted and pivoted array*/
/* Standard Binary Search function*/
function binarySearch( arr, low,
high, key){
if (high < low)
return -1;
let mid = Math.floor((low + high) / 2); /*low + (high - low)/2;*/
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
// else
return binarySearch(arr, low, (mid - 1), key);
}
/* Function to get pivot. For array 3, 4, 5, 6, 1, 2
it returns 3 (index of 6) */
function findPivot( arr, low, high){
// base cases
if (high < low)
return -1;
if (high == low)
return low;
let mid = Math.floor((low + high) / 2); /*low + (high - low)/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);
}
/* Searches an element key in a pivoted
sorted array arr[] of size n */
function pivotedBinarySearch( arr, n, key){
let pivot = findPivot(arr, 0, n - 1);
// If we didn't find a pivot,
// then array is not rotated at all
if (pivot == -1)
return binarySearch(arr, 0, n - 1, key);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] == key)
return pivot;
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
/* Driver program to check above functions */
// Let us search 3 in below array
let arr1 = [ 5, 6, 7, 8, 9, 10, 1, 2, 3 ];
let n = arr1.length;
let key = 3;
// Function calling
document.write( "Index of the element is : "
+ pivotedBinarySearch(arr1, n, key));
</script>
Output:
Index of the element is : 8
Complexity Analysis:
- Time Complexity: O(log n).
Binary Search requires log n comparisons to find the element. So time complexity is O(log n). - Space Complexity:O(1), No extra space is required.
Thanks to Ajay Mishra for initial solution.
Improved Solution:
Approach: Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key.
1) Find middle point mid = (l + h)/2
2) If key is present at middle point, return mid.
3) Else If arr[l..mid] is sorted
a) If key to be searched lies in range from arr[l]
to arr[mid], recur for arr[l..mid].
b) Else recur for arr[mid+1..h]
4) Else (arr[mid+1..h] must be sorted)
a) If key to be searched lies in range from arr[mid+1]
to arr[h], recur for arr[mid+1..h].
b) Else recur for arr[l..mid]
Below is the implementation of above idea:
JavaScript
<script>
// Search an element in sorted and rotated
// array using single pass of Binary Search
// Returns index of key in arr[l..h] if
// key is present, otherwise returns -1
function search(arr, l, h, key){
if (l > h)
return -1;
let mid = Math.floor((l + h) / 2);
if (arr[mid] == key)
return mid;
/* If arr[l...mid] is sorted */
if (arr[l] <= arr[mid]) {
/* As this subarray is sorted, we can quickly
check if key lies in half or other half */
if (key >= arr[l] && key <= arr[mid])
return search(arr, l, mid - 1, key);
/*If key not lies in first half subarray,
Divide other half into two subarrays,
such that we can quickly check if key lies
in other half */
return search(arr, mid + 1, h, key);
}
/* If arr[l..mid] first subarray is not sorted,
then arr[mid... h]
must be sorted subarray */
if (key >= arr[mid] && key <= arr[h])
return search(arr, mid + 1, h, key);
return search(arr, l, mid - 1, key);
}
// Driver program
let arr = [ 4, 5, 6, 7, 8, 9, 1, 2, 3 ];
let n = arr.length;
let key = 6;
let i = search(arr, 0, n - 1, key);
if (i != -1)
document.write("Index: " +i +"
");
else
document.write("Key not found");
</script>
Output:
Index: 2
Complexity Analysis:
- Time Complexity: O(log n).
Binary Search requires log n comparisons to find the element. So time complexity is O(log n). - Space Complexity: O(1).
As no extra space is required.
Thanks to Gaurav Ahirwar for suggesting above solution.
How to handle duplicates?
It doesn't look possible to search in O(Logn) time in all cases when duplicates are allowed. For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}.
It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle.
Similar Articles:
Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem.
Please refer complete article on
Search an element in a sorted and rotated array for more details!
Similar Reads
Javascript Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above ar
3 min read
Search an element in a sorted and rotated array with duplicates
Given a sorted and rotated array arr[] and a key, the task is to find whether key exists in the rotated array (with duplicates).Examples: Input: arr[] = [3, 3, 3, 1, 2, 3], key = 3 Output: trueExplanation: arr[0] = 3Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 11 Output: falseExplanation: 11 is not pres
6 min read
Maximum element in a sorted and rotated array
Given a sorted array arr[] (may contain duplicates) of size n that is rotated at some unknown point, the task is to find the maximum element in it. Examples: Input: arr[] = {5, 6, 1, 2, 3, 4}Output: 6Explanation: 6 is the maximum element present in the array.Input: arr[] = {3, 2, 2, 2}Output: 3Expla
7 min read
Javascript Program to Find Mth element after K Right Rotations of an Array
Given non-negative integers K, M, and an array arr[ ] consisting of N elements, the task is to find the Mth element of the array after K right rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1 Output: 5 Explanation: The array after first right rotation a1[ ] = {23, 3, 4, 5} The array a
8 min read
Search an element in a reverse sorted array
Given an array arr[] sorted in decreasing order, and an integer X, the task is to check if X is present in the given array or not. If X is present in the array, print its index ( 0-based indexing). Otherwise, print -1. Examples: Input: arr[] = {5, 4, 3, 2, 1}, X = 4Output: 1Explanation: Element X (=
8 min read
Javascript Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= .....Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR {
4 min read
Search for an element in a Mountain Array
Given a mountain array arr[] and an integer X, the task is to find the smallest index of X in the given array. If no such index is found, print -1. Examples: Input: arr = {1, 2, 3, 4, 5, 3, 1}, X = 3Output: 2Explanation: The smallest index of X(= 3) in the array is 2. Therefore, the required output
14 min read
Javascript Program to Find the Mth element of the Array after K left rotations
Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation:Â The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ]
2 min read
Javascript Program For Sorting An Array Of 0s, 1s and 2s
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples:Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0
5 min read
Binary search in an object Array for the field of an element
What is Binary Searching?Binary searching is a type of algorithm that can quickly search through a sorted array of elements. The algorithm works by comparing the search key to the middle element of the array. If the key is larger than the middle element, the algorithm will search the right side of t
8 min read