JavaScript Program to Count rotations required to sort given array in non-increasing order


We will be writing a program to count the number of rotations required to sort an array in non-increasing order. The program will use a loop to traverse the array and keep track of the maximum element found so far. When a smaller element is found, we will increment the rotation count and update the maximum element. In the end, the rotation count will be returned as the result of the program. This program will help us efficiently sort the array and determine the number of rotations required to achieve a non-increasing order.

Approach

The approach to counting rotations required to sort an array in non-increasing order is as follows −

  • Split the array into two parts: a sorted part and an unsorted part.

  • The number of rotations required is equal to the number of elements in the sorted part.

  • To find the sorted part, traverse the array from right to left and keep track of the maximum element.

  • When a smaller element is found, break the loop and return the length of the sorted part.

  • If the loop completes, the whole array is sorted, so return 0.

Example

Here is a complete example in JavaScript to count the number of rotations required to sort an array in non-increasing order −

function countRotations(arr) {
   let n = arr.length;
   let minIndex = 0;
   let minValue = arr[0];
   
   // Find the minimum element
   for (let i = 1; i < n; i++) {
      if (arr[i] < minValue) {
         minIndex = i;
         minValue = arr[i];
      }
   }
   // Return the number of rotations
   return minIndex;
}
let arr = [15, 18, 2, 3, 6, 12];
console.log("The number of rotations required to sort the array in non-increasing order is:", countRotations(arr));

Explanation

  • The function countRotations takes an array as an argument.

  • n is initialized to the length of the array.

  • minIndex and minValue are initialized to 0 and the first element of the array, respectively.

  • The for loop iterates through the array, starting from the second element, to find the index and value of the minimum element in the array. If a smaller element is found, minIndex and minValue are updated to its index and value.

  • Finally, the function returns minIndex, which is the number of rotations required to sort the array in non-increasing order.

In this example, the array is [15, 18, 2, 3, 6, 12], and the minimum element is 2, located at index 2. To sort the array in non-increasing order, the 2 must be placed at the end of the array, so the number of rotations required is 2.

Updated on: 13-Mar-2023

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements