Skip to content

Instantly share code, notes, and snippets.

@uttesh
Created September 5, 2018 17:42
Show Gist options
  • Save uttesh/edb187a38ac67ebf758a17ce5b4a02c6 to your computer and use it in GitHub Desktop.
Save uttesh/edb187a38ac67ebf758a17ce5b4a02c6 to your computer and use it in GitHub Desktop.
Java circular array/rotate array, A left rotation operation on an array of size shifts each of the array's elements unit to the left.
public class CircularArray {
public static int[] arr = { 1, 2, 3, 4, 5 };
public static void main(String[] args) {
System.out.println(Arrays.toString(arr));
int rotation = 4;
rotateArray(arr, rotation);
System.out.println(Arrays.toString(arr));
}
public static void rotateArray(int[] temp, int count) {
if (count != 0) {
int lastElementIndex = temp.length - 1;
int element = temp[0];
for (int j = 0; j < temp.length; j++) {
if (j + 1 < temp.length)
temp[j] = temp[j + 1];
}
temp[lastElementIndex] = element;
count = count-1;
rotateArray(temp, count);
}
}
}
@uttesh
Copy link
Author

uttesh commented Sep 5, 2018

Instead of the recursive function, just make the plain method and call from the for loop for the better performance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment