Program to Find position from which sorted array has been rotated in java


In this core java programming tutorial we will Write a Program to Find position from which sorted array has been rotated in java.
You are given a sorted array but it has been rotated, Find position from which sorted array has been rotated in java.



But how array is rotated?

Let’s understand rotation of array by diagrams -


Our initial array is -
 

Rotate the array -

Array formed after rotation -
   
Now, we could say array is rotated from third position i.e. at 1.



Likewise, we rotated String in rotational palindrome.



Let’s take few more example arrays in java >
1, 2, 3, 4  - Array has not been rotated

2, 3, 4, 1  - Array has been rotated from 3 position

3, 4, 1, 2  - Array has been rotated from 2 position

4, 1, 2, 3  - Array has been rotated from 1 position


Example/ Full Program/SourceCode to Find position from which sorted array has been rotated in java >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class FindPositionFromWhichSortedArrayRotatedExample {
  
   public static void main(String[] args) {
          int ar[] = { 4, 1, 2, 3 };
          for (int n : ar)
                 System.out.print(n + " ");
          System.out.print(" : ");
         
          for (int i = 0; i < ar.length; i++) {
                 if (i + 1 == ar.length) {
                       System.out.println("Array has not been rotated");
                 } else {
                       if (ar[i] > ar[i + 1]) {
                              System.out.println("Array has been rotated from " + (i+1)
                                            + " position");
                              break;
                       }
                 }
          } //end for loop
   }
}
/* output
4 1 2 3  : Array has been rotated from 1 position
*/



So in this core java programming tutorial we wrote a Program to Find position from which sorted array has been rotated in java.
You were given a sorted array but it was rotated, we found position from which sorted array was rotated in java.



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

>Pattern/Pyramid generating programs









eEdit
Must read for you :