Finding smallest element in a sorted array which is rotated in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 19-Jan-2021 11:02:43
Advertisements