Tuesday 29 May 2018

Java Program to find number of times sorted array has been rotated



Sample Program:-


public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 4, 1, 2, 3 };  
           for (int i = 0; i < ar.length; i++) {  
                if (i + 1 == ar.length) {  
                     System.out.println("Array is not rotated");  
                } else {  
                     if (ar[i] > ar[i + 1]) {  
                          System.out.println("Array has been rotated by " + (i + 1) + " position");  
                          break;  
                     }  
                }  
           }  
      }  
 }  


Output:-


Array has been rotated by 1 position  

Enjoy Coding.

No comments:

Post a Comment