Searching 42

QUESTION

Consider an array of distinct numbers sorted in increasing order. The array has been rotated (anti-clockwise) k number of times. Given such an array, find the value of k. The number of elements in the array and the elements of the array are the input.

“TESTCASE_1”: “6\n15 18 2 3 6 12\n###—###SEPERATOR—###—\n2”, “TESTCASE_2”: “5\n7 9 11 12 5\n###—###SEPERATOR—###—\n4”, “TESTCASE_3”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

// Java program to find number of 
// rotations in a sorted and rotated
// array.
import java.util.*;
import java.lang.*;
import java.io.*;
 
class TestClass
{
    // Returns count of rotations for an 
    // array which is first sorted in 
    // ascending order, then rotated
    static int countRotations(int arr[], int n)
    {
        // We basically find index of minimum
        // element
        int min = arr[0], min_index = -1;
        for (int i = 0; i < n; i++)
        {
            if (min > arr[i])
            {
                min = arr[i];
                min_index = i;
            }
        } 
        return min_index;
    }
 
    // Driver program to test above functions
    public static void main (String[] args) 
    {
      Scanner sc=new Scanner(System.in);
      int n=sc.nextInt();
      int arr[]=new int[n];
      for(int i=0;i<n;i++)
        arr[i]=sc.nextInt();
      
     
        System.out.println(countRotations(arr, n));
    }
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock