Reputation: 55
Hi how come swapping technique(my code) suffers Timeout where as circular array
{(i+number of rotation)%length}
implementation does not?
a
is an int[]
.
for (int i = 0; i < numberofrotation; i++) {
for (int j = 0; j < a.length-1; j++) {
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
return a;
Upvotes: 0
Views: 134
Reputation: 960
(i+number of rotation)%length is to advance by number of rotations and wrap around to form circular array. With modulo number of rotations are reduced to less than or equals to length of array, hence faster execution
To give you some idea...
Taking your approach of swapping array values, if an array of length 10 is swapped by n times where n is a multiple of 10 , means n mod 10 = 0, than result is original array.
If value of n is not a multiple of 10 than you will see array order change in array values.
you can get the result either by rotating n times, or same result can be achieved by rotating n mod 10 times
So if n = 25 than swapping array by 25 is equivalent to swapping array 5 times
25 mod 10 = 5
similarly if n=13 , than swapping array by 13 time will have same result of swapping array 3 times
13 mod 10 = 3
Even if number of rotation is Integer.MAX_VALUE and length of array to rotate is 100, number of rotations can be reduced to Integer.MAX_VALUE%100 which is 47.
Upvotes: 1