Donate : Link
Medium Blog : Link
Applications : Link
Write a function rotate(array[], x) that rotates array[] of size n by x elements.
| 1 | 2 | 3 | 4 | 5 |
Rotation of the above array by 2 will make array
| 3 | 4 | 5 | 1 | 2 |
Please first try to do it yourself, then move to the solution.
1) Rotate array from x to length and store elements into newArray.
2) Rotate array from 0 to x and store elements into newArray.
Program
package com.test;
import java.util.Arrays;
/**
* @author code.factory
*/
public class Test {
public static void main(String... strings) {
int array[] = new int[] {10, 20, 30, 40, 50};
rotate(array, 0);
rotate(array, 34);
rotate(array, 3);
}
static void rotate(int array[], int x) {
int length = array.length;
int newArray[] = new int[length];
x = x % length; // set x to b/w o to length of array so it will not traverse more
// Rotate array using 2 loop
for (int i = x; i < length; i++) {
newArray[i - x] = array[i];
}
for (int j = 0; j < x; j++) {
newArray[length - x + j] = array[j];
}
System.out.println(Arrays.toString(newArray));
newArray = new int[length];
// Rotate array using 1 loop
for (int j = 0; j < length; j++) {
if (j >= x) {
newArray[j - x] = array[j];
} else {
newArray[length - x + j] = array[j];
}
}
System.out.println(Arrays.toString(newArray));
}
}
Output:
[10, 20, 30, 40, 50]
[10, 20, 30, 40, 50]
[50, 10, 20, 30, 40]
[50, 10, 20, 30, 40]
[40, 50, 10, 20, 30]
[40, 50, 10, 20, 30]

