Im making a method that shifts chars in an array both left and right with a parameter that tells how many times to shift. It has to finish within 20 milliseconds, so i tried recursion.
//Method that switches place in array
public static void bytt(char[] c, int i, int j){
char temp = c[i];
c[i] = c[j];
c[j] = temp;
}
//This method shifts left
public static char rotasjon1(char[] a, int i){
if(i > 0){
bytt(a,i,i-1);
return rotasjon1(a,i-1);
}
else
return ' ';
}
//This method shifts right
public static char reverseRotasjon(char[] a, int i){
if(i < a.length-1){
bytt(a,i,i+1);
return reverseRotasjon(a,i+1);
}
else
return ' ';
}
//This method decides to use right shift or left shift depending on the parameter
public static void rotasjon(final char[] a, int k){
if(a.length == 1 || a.length == 0){
return;
}
if(k >= 0){
for(int i = 0; i< k; i++){
char temp = a[a.length-1];
rotasjon1(a,a.length-1);
a[0] = temp;
}
}
if(k < 0){
for(int i = k; i< 0; i++) {
char temp = a[0];
reverseRotasjon(a, 0);
a[a.length - 1] = temp;
}
}
}
//All these work fine with this array
char[] d = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
char[] d0 = {'G', 'H', 'I', 'J', 'A', 'B', 'C', 'D', 'E', 'F'};
Oblig1.rotasjon(d, 4);
d = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
Oblig1.rotasjon(d, -6);
//But i get java.lang.StackOverflowError
with this array
char[] x = new char[100_000];
Oblig1.rotasjon(x, 99_999);
I know the array is big an stuff, but is it possible to fix this or do i have to go back to traditional for loops ? it have to execute within 20 millisecods