I have to re write my implementation vor insert/selection-sort in Java from PHP. So, the algorithms work fine but as it's a pain in the rear to work with all the different types when writing a quick programm I'm using a Logger Class in order to save my multi-type values.
As I haven't worked with Java for a while, there might be a problem in the code that causes this weird bug.
I have to iterate over an Integer Array in order to generate and sort random Arrays of different lengths:
public static Log[][] eval(Integer[] sizes, Algorithm alg){
Log[][] logs = new Log[sizes.length][2];
for (int i = 0; i < sizes.length; i++) {
Log[] tmp = new Log[3];
Integer[] rand = randomArray(sizes[i]);
System.out.println("Before "+Arrays.toString(rand));
tmp[0] = new Log(sizes[i], rand);
tmp[1] = alg.insertionSort(rand);
tmp[2] = alg.selectionSort(rand);
System.out.println("After "+Arrays.toString(rand));
logs[i] = tmp;
}
return logs;
}
As you see, there are 2 debugs, which will give something like this:
Before [2, 1, 4, 5, 3]
After [1, 2, 3, 4, 5]
Before [1, 8, 9, 10, 5, 4, 2, 6, 7, 3]
After [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Before [11, 15, 20, 16, 18, 8, 4, 13, 2, 19, 12, 3, 10, 5, 17, 14, 1, 9, 6, 7]
After [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
This is strange, as I doesnt change the rand value. Even if I put an Int array called backup outside the loop and overwrite it and print out this in the last log, it's still a sorted array. I'm trying to fix this for over a hour and I can't find the bug. It must be within the algorithm methodes for index 1/2, because Before == After when skipping these lines. But I have no clue, what's wrong, as I'm only using the array as parameter and return an Object of Log.
Here's one algorithm-method:
public Log insertionSort(Integer[] sortieren) {
double startTime = System.nanoTime();
int temp;
for (int i = 1; i < sortieren.length; i++) {
temp = sortieren[i];
int j = i;
while (j > 0 && sortieren[j - 1] > temp) {
sortieren[j] = sortieren[j - 1];
j--;
}
sortieren[j] = temp;
}
double stopTime = System.nanoTime();
double time = stopTime - startTime;
Log log = new Log("Insertion-Sort", (time/1000000), sortieren);
return log;
}
And this is my Log Class:
public class Log {
public String name;
public double time;
public int size;
public Integer[] sorted;
public Integer[] randArray;
public Log(String name, double time, Integer[] sorted){
this.name = name;
this.time = time;
this.sorted = sorted;
}
public Log(int size, Integer[] random){
this.size = size;
this.randArray = random;
}
}
Later, I want to evalue this through this method:
public static void reportLogger(Log[][] log, boolean showArray){
for (int i = 0; i < log.length; i++) {
// Show Initial Array (0th Index) -> (size, array)
for (int j = 1; j <= 2 ; j++) {
Log tmp = log[i][j];
// 1st/2nd Index -> Insert/Selection -> name, time, sortedArray by using tmp.name ,etc..
System.out.println("---------------------");*/
}
}