First one is definitely better. More variables you have, the harder it is to follow them. That said, I'd suggest applying some rules:
A <=
comparison is very unusual and triggers an unnecessary attention
Declare a variable in the scope it it used in
Recognize important algorithms and factor them out
A loop usually represent an important algorithm
Let's apply the first rule:
public static int[] selection(int[] tab) {
int minor;
int aux;
for (int i=0; i<tab.length-1; i++) {
minor = tab[i];
for (int j=i+1; j<tab.length; j++) {
if (tab[j] < minor) {
aux = tab[j];
tab[j] = minor;
minor = aux;
}
}
tab[i] = minor;
}
return tab;
}
Then the second:
public static int[] selection(int[] tab) {
for (int i=0; i<tab.length-1; i++) {
int minor = tab[i];
for (int j=i+1; j<tab.length; j++) {
if (tab[j] < minor) {
int aux = tab[j];
tab[j] = minor;
minor = aux;
}
}
tab[i] = minor;
}
return tab;
}
The code in if
clause is one of the most fundamental algorithms, namely swap
. I am afraid Java doesn't support swapping the way C++ programmers use; we just can't pass an integer to a function to have it modified. In this particular case Java "deficiency" pushes us to the right direction: what we actually want is to swap values in array - no need for minor
at all! Here is an application of a third rule (with swap
provided separately):
public static int[] selection(int[] tab) {
for (int i=0; i<tab.length-1; i++) {
for (int j=i+1; j<tab.length; j++) {
if (tab[j] < tab[i]) {
swap(tab, i, j);
}
}
}
return tab;
}
Now we may focus on the fourth rule: what does the inner loop represent? A swap
which finally settle the value of tab[i]
is the smallest tab[j]
in the range. This would be my final code (index_of_min
provided separately):
public static int[] selection(int[] tab) {
for (int i=0; i<tab.length-1; i++) {
int index_of_min = index_of_minimum(tab, i + 1, tab.length);
if (tab[index_of_min] < tab[i]) {
swap(tab, i, index_of_min)
}
}
return tab;
}
BTW, now an opportunistic optimization is obvious (I am not sure I'd go for it but anyway):
public static int[] selection(int[] tab) {
for (int i=0; i<tab.length-1; i++) {
int index_of_min = index_of_minimum(tab, i + 1, tab.length);
if (tab[index_of_min] >= tab[i]) {
++i;
}
swap(tab, i, index_of_min);
}
return tab;
}