Suggestions
I guess you are coming from a C/C++ background. Java arrays have a property called length
, which gives its size, so you don't need the parameter n
. Just use arr.length
wherever you have used n
.
I actually once thought that swapping the first element with every other element d
times was an original algorithm for rotating an array I had thought up myself, and it's in-place but this has a time complexity of O(n*d)
. There exists a better algorithm working in O(n)
time, which uses the idea: Instead of moving one by one, divide the array into different sets where the number of sets is equal to the GCD of n
and d
and move the elements within the sets.
In Java, the code would look like this (note: This only does a left rotation):
void rotate(int[] arr, int d) {
int i, j, k, temp;
for (i = 0; i < gcd(d, arr.length); i++) {
/* move i-th values of blocks */
temp = arr[i];
j = i;
while (1 != 0)
{
k = j + d;
if (k >= arr.length)
k = k - arr.length;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}
/*Function to get gcd of a and b*/
int gcd(int a, int b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
This version of rotate(int[], int)
rotates the passed array in-place, so you can just print out the elements in a loop later. For printing, hoping you are on JDK 5 or greater, use the for-each loop:
for(int element : arr) {
System.out.println(element);
}
And why restrict yourself to arrays of ints? With generics, you could have the following modifications and make this rotation routine work with all types of arrays of objects (note that int
is not an object, it is a primitive type, you'll need to use Integer
, which is the object-oriented wrapper type for int
, instead of int
. Same goes for double
and other primitive types, you'll need to use arrays of their wrapper types, look this up).
<T> void rotate(T[] arr, int d) {
int i, j, k;
T temp;
...
Style
You have inconsistent indentation and spacing. If you are using some very simple text editor like Notepad for writing your programs, you might one check out editors with auto-formatting of code, or use an IDE. Also, you don't have proper whitespace surrounding binary operators. Finally, your variable names are somewhat nondescriptive, but in this case it would have been OK if you had properly documented your methods.