I want to reverse and array of integer recursively, I think this is the way but I get this error when trying with a 5 integer array:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at name.of.package.ArrayAscDesc.CambioAscDesc(ArrayAscDesc.java:12)
at name.of.package.ArrayAscDesc.main(ArrayAscDesc.java:34)
Here's the code:
import java.util.Scanner;
public class ArrayAscDesc {
public static int[] CambioAscDesc (int[] array, int index, int tam){
while(index < tam){
int temp = array[index];
array[index] = array[tam];
array[tam] = temp;
CambioAscDesc(array, index++, tam--);
}
return array;
}
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.print("Inserte el tamaño del array: ");
int tam = teclado.nextInt();
int[] array = new int[tam];
System.out.println("Inserte datos para un array de " + tam + " elementos:");
for(int i=0; i<tam; i++)
{array[i]= teclado.nextInt();}
System.out.print(CambioAscDesc(array, 0, tam));
}
}
Thanks beforehand!