Created
September 5, 2018 17:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of the recursive function, just make the plain method and call from the for loop for the better performance