Array Rotator1
Array Rotator1
Email : [email protected]
Blog : gmanikandan.wordpress.com
Mobile : +91-9944306848
General things about rotating array of elements to the Right and the Left
// In this notes where ever you see (N and n_ have the below things in mind
// N = denotes the length of the array we handle
// n = denotes that much time we want to rotate the array
rotating right by one place:
rotating each elements of array by one place towards right,
here the last element will become the first one after rotating
rotating left by one place:
rotating each elements of array by one place towards left, here
the first element will become the last one after rotating.
Eg of Right rotating:
1
( the above array is rotated right 3 times when compared to its initial state)
( the above array is rotated right 5 times when compared to its very initial state)
Eg of Left rotating:
1
( the above array is rotated left 2 times when compared to its very initial state)
array to its very initial state (the state where no rotating is done)
In the above example of left rotating note that, after rotating 5 times towards
left we got our Array back as it was in the very initial state. By the using above
rule we can write like this.
Array[ newPosition ];
newPosition = (newPosition
+ n) mod N;
}
return array;
}
//end
see we get only 0 and 2 as newPositions before we finish 4 iteration and this is
the state we mean as Cycle...
*/
if (newPosition == 0) {
return array;
}// check is there any cycles and handle it specially
else if (newPosition!= 1
&&
isThereCycleWhileIteration(array.length, newPosition))
{
array = rotateArray(array, newPosition - 1);
return rotateArray(array, 1);
}// else handle it normally
else {
return rotateArray(array, newPosition);
}
}
// the below method returns true if firstPosition equals any other
// nextPosition before we finish iteration
private boolean isThereCycleWhileIteration(int arrayLenght, int position) {
int firstPosition = (0 + position) % arrayLenght;
int nextPostion = firstPosition;
for (int i = 1; i < arrayLenght; i++) {
nextPostion = (nextPostion + position) % arrayLenght;
if (nextPostion == firstPosition) {
return true;
}
}
return false;
}
// the method which implements my algorithm and it does rotating towards right
private T[] rotateArray(T[] array, int position) {
int newPosition = 0;
T temporaryVariable = array[newPosition];
T anotherTemporayVariable;
for (int count = 0; count < array.length; count++) {
newPosition = (newPosition + position) % (array.length);
anotherTemporayVariable = array[newPosition];
array[newPosition] = temporaryVariable;
temporaryVariable = anotherTemporayVariable;
}
return array;
}
}