Im currently trying to develop a program in Java that has to print the steps an algorithm takes to order the elements in an array (all the elements in the array each time it changes), where print means displaying it in console, saving it as a file or in a SwingComponent.
Right now im using an Arraylist< int[] > to save the steps, but it only allows me to sort less than 1k elements before throwing an exception.
Is there anyway I can save the steps for more elements?
Code
package tests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BubbleSort{
public void sort( int[] array, List<int[]> process ){
int len = array.length - 1;
int i, j, tmp;
process.add( array.clone() ); //Save original array
for( i = 0; i < len; ++i ){
for( j = 0; j < len - i; ++j ){
if( array[ j ] > array[ j + 1 ] ){
tmp = array[ j ];
array[ j ] = array[ j + 1 ];
array[ j + 1 ] = tmp;
process.add( array.clone() ); //Array changed, save it
}
}
}
}
//creates a random array
public static int[] randomIntegerArray( int min, int max, int amount ){
int[] array = new int[ amount ];
int total = max - min;
List< Integer > numbers = new ArrayList<>( total );
int i = 0;
for( i = min; i < max; ++i ){
numbers.add( i );
}
Collections.shuffle( numbers );
for( i = 0; i < amount; ++i ){
array[ i ] = numbers.remove( 0 );
}
return array;
}
public static void main( String[] args ){
BubbleSort bubbleSort = new BubbleSort();
List<int[]> process = new ArrayList<>();
int[] noError = randomIntegerArray( 0, 1000, 500 ); //Works up ~ 900
int[] error = randomIntegerArray( 0, 1000, 1000 );
bubbleSort.sort( noError, process);// Works
//bubbleSort.sort( error, process);// throws java.lang.OutOfMemoryError: Java heap space in line 22
//Print steps
//for( int[] a : process ){ System.out.println( Arrays.toString( a ) ); }
}
}