- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding smallest element in a sorted array which is rotated in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the only argument.
The array is first sorted and then rotated by any arbitrary number of elements. Our function should find the smallest element in the array and return that element.
The only condition is that we have to do this in less than linear time complexity, maybe using a somewhat tweaked version of the binary search algorithm.
For example −
If the input array is −
const arr = [6, 8, 12, 25, 2, 4, 5];
Then the output should be 2.
Example
Following is the code −
const arr = [6, 8, 12, 25, 2, 4, 5]; const findMin = (arr = []) => { let temp; let min = 0; let max = arr.length - 1; let currentMin = Number.POSITIVE_INFINITY; while (min <= max) { temp = (min + max) >> 1; currentMin = Math.min(currentMin, arr[temp]); if (arr[min] < arr[temp] && arr[temp] <= arr[max] || arr[min] > arr[temp]) { max = temp - 1; } else if (arr[temp] === arr[min] && arr[min] === arr[max]) { let guessNum = arr[temp]; while (min <= max && arr[min] === guessNum) { min++; } } else { min = temp + 1; } } return currentMin; }; console.log(findMin(arr));
Output
Following is the console output −
2
- Related Articles
- Maximum element in a sorted and rotated array in C++
- Finding first unique element in sorted array in JavaScript
- Finding the first unique element in a sorted array in JavaScript
- Nth smallest element in sorted 2-D array in JavaScript
- C++ program to search an element in a sorted rotated array
- Search in Rotated Sorted Array in Python
- Finding desired numbers in a sorted array in JavaScript
- Search in Rotated Sorted Array II in C++
- Find Minimum in Rotated Sorted Array in C++
- Search in Rotated Sorted Array II in Python
- Check if an array is sorted and rotated in Python
- Check if an array is sorted and rotated in C++
- Find Minimum in Rotated Sorted Array II in C++
- Find the Rotation Count in Rotated Sorted array in C++
- Program to check whether an array Is sorted and rotated in Python

Advertisements