
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Smallest Element in Rotated Sorted Array 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
Advertisements