Last active
August 29, 2015 14:04
-
-
Save pavelnganpi/7a009fa1e85117a75d7a to your computer and use it in GitHub Desktop.
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. * @author paveynganpi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. | |
* @author paveynganpi | |
* | |
*/ | |
//reversal solution | |
/** | |
* | |
* Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. | |
* @author paveynganpi | |
* | |
*/ | |
public class ProgramForArrayRotation { | |
public static void leftRotate(int[] arr, int d, int n){ | |
reverse(arr,0,d-1); | |
reverse(arr,d,n-1); | |
reverse(arr,0,n-1); | |
} | |
public static void printArr(int[] arr){ | |
for(int i=0;i<arr.length;i++){ | |
System.out.print( arr[i] + " "); | |
} | |
System.out.println(); | |
} | |
public static void reverse(int[] arr,int start, int end){ | |
int i; | |
int temp; | |
while(start < end) | |
{ | |
temp = arr[start]; | |
arr[start] = arr[end]; | |
arr[end] = temp; | |
start++; | |
end--; | |
} | |
} | |
public static void main(String[]main){ | |
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; | |
printArr(arr); | |
System.out.println(); | |
leftRotate(arr,3,arr.length); | |
printArr(arr); | |
} | |
} | |
//gcd solution | |
public class ProgramForArrayRotation { | |
public static void leftRotate(int[] arr, int d, int n){ | |
int i; | |
int j; | |
int k; | |
int temp; | |
for(i=0; i<gcd(d,n); i++){ | |
j=i; | |
temp = arr[i]; | |
while(true){ | |
k = j+d; | |
if(k>=n){ | |
k=k-n; | |
} | |
if(k==i){ | |
break; | |
} | |
arr[j] = arr[k]; | |
j=k; | |
} | |
arr[j] = temp; | |
} | |
} | |
public static void printArr(int[] arr){ | |
for(int i=0;i<arr.length;i++){ | |
System.out.print( arr[i] + " "); | |
} | |
} | |
public static int gcd(int a , int b){ | |
if(b==0){return a;} | |
else{ | |
return gcd(b,a%b); | |
} | |
} | |
public static void main(String[]main){ | |
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; | |
printArr(arr); | |
System.out.println(); | |
leftRotate(arr,3,arr.length); | |
printArr(arr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment