I was doing the MergeSort sorting algorithm in Java for study purposes and every time it runs it gives error. I have already reviewed the logic of the algorithm, I already replace the array of integers with a ArrayList
, I already tried to change the parsing 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 exit prompt along with the error message, I get this:
The array was almost completely ordered.
I want to know what the problem is with my code and what the possible solution is.