3
I was doing the Mergesort sorting algorithm in Java for study purposes and every time it runs it gives error. I’ve already revised the logic of the algorithm, already replacing the array of integers with a ArrayList
, I’ve tried to change the stopping logic but nothing.
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<>();
array.add(0);
array.add(3);
array.add(9);
array.add(18);
array.add(5);
array.add(4);
array.add(6);
array.add(10);
MergeSortClass.dividir( array, 0, array.size() );
System.out.println( array.toString() );
}
public static void dividir( ArrayList<Integer> array, int inicio, int fim ){
if( inicio < fim ){
int meio = ( inicio + ( fim - 1 ) ) / 2;
dividir( array, inicio, meio );
dividir( array, meio + 1, fim );
intercalar( array, inicio, meio, fim );
}
}
public static void intercalar( ArrayList<Integer> array, int inicio, int meio, int fim ){
int i = inicio;
int j = meio + 1;
ArrayList<Integer> temp = new ArrayList<>();
while( i < j && j < fim ){
if( array.get(i) < array.get(j) ){
temp.add( array.get(i) );
i++;
} else {
temp.add( array.get(j) );
j++;
}
}
//No caso da árvore recursiva estar desbalanceada e um dos lados terminar de comparar, o restante do outro lado será copiado para o array temporário
while( i < j ){
temp.add( array.get(i) );
i++;
}
while( j < fim ){
temp.add( array.get(j) );
j++;
}
for( i = 0; i < temp.size(); i++ ){
array.set( i + inicio, temp.get(i) );
//código abaixo só para testar
System.out.println( array.get(i + inicio) );
}
System.out.println("");
}
After I run the code, at the output prompt along with the error message, I get it:
The array has been almost fully ordered.
I want to know what is the problem with my code and what is the possible solution.
You are offending the size of the array, this is what the error is showing. For some reason you ordered in a position outside the range
[0, array.size())
– Jefferson Quesado
Related: https://answall.com/q/235616/64969
– Jefferson Quesado
The error is not compilation, it is in execution, so much so that it prints some results.
– prmottajr