public int[] selectionSort(int array[]) {
for(int i = array.length - 1; i >= 0; i--) {
int highestIndex = i;
for(int j = i; j >= 0; j--) {
if(array[j] > array[highestIndex])
highestIndex = j;
}
int temp = array[i];
array[i] = array[highestIndex];
array[highestIndex] = temp;
}
return array;
}
I understand the concept of selection sort, but the code is confusing me. Specifically, can someone explain what is happening in the last three statements of the outer for-loop starting with "int temp = array[i];"
This is the famous swapping routine. In languages like Java, when you want to swap the values of two variables named say a
and b
, you have to resort to such a routine where you use a third variable to hold a value in transit:
int a = 2;
int b = 6;
int tmp = a; // now tmp has a value that is _copy_ of a i.e. 2
a = b; // since we saved a in tmp, we can _mutate_ it, now a has b's value
b = tmp; // swap! here, b = a won't work because a contains b's current value.
// now a has value 6 and b has value 2, exactly what we wanted.
In some other languages, a construct like a, b = b, a
is available for this purpose, which is more intuitive in my opinion.
In selection sort, after the inner loop has found the index of the element that holds the highest value, you need to swap it with the element held by the outer loop index and that's what this achieves in that context.