I'm a newbie studying java and in my notes I found the following code (a code that I know is simple, but my head hasn't rationalized it yet, and I wanted to see if you could help me a little...):
public static Clasificable[] clasificar(Clasificable[] array) {
int i, j;
Clasificable c;
for (i = 0; i < array.length; i++) {
for (j = i + 1; j < array.length; j++) {
if (array[j].compare(array[i]) == Clasificable.INFERIOR) {
c = array[j];
array[j] = array[i];
array[i] = c;
} else if (array[j].compare(array[i]) == Clasificable.ERROR) {
return null;
}
}
}
return array;
}
Why do we create i
and j
exactly? Why would we add a 1 to the i
in the second for
? Yes, I know these are quite silly questions, but really my mind has not reached there yet, and I would like to understand it and get there, so if someone sees the need to explain it to me as a 4-year-old, I ask you to please Do it...
The value of LOWER, etc would be:
public static final int INFERIOR=-1;
public static final int IGUAL=0;
public static final int SUPERIOR=1;
public static final int ERROR=-99;
It is an implementation of the insertion sort algorithm .
We use
i
andj
because there are two nested loops, the outer one iterates through the entire array and the inner one iterates, for each value ofi
, the rest of the array to see if it finds a value less than positioni
to replace it if it finds it.Clasificable
it looks like just an extension ofjava.util.Comparable
to which four constant values have been added to the values it returnsjava.util.Comparable.compare(Object)
. It's not very useful, and it messes more than it helps.You have an array that you want to loop through:
Now imagine that you want, for each position, to do an operation with the rest of subsequent positions: That means that for each position, you want to traverse the array again. If you
i
indicate the position of the current element, you createj
to iterate through the positions of the rest of the elements. And since you want to start with the position right after the current one, then the easiest thing is to add one to it:If you join the two loops, nesting them, you will have a code like the one you have put.