-2
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];"

Guy Fieri
  • 35
  • 7
  • 1
    http://stackoverflow.com/questions/13766209/effective-swapping-of-elements-of-an-array-in-java – Sotirios Delimanolis Jun 07 '16 at 21:46
  • You switch the places of `array[i]` and `array[highestIndex]`. To do that you make a copy of `array[i]` so you can access the value after it has been overwritten by `array[i] = array[highestIndex];`. – RaminS Jun 07 '16 at 21:47

1 Answers1

2

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.

Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
  • Thank you, this was what I was looking for. I knew that two values were being swapped, but I didn't understand how it affected the rest of the code. – Guy Fieri Jun 07 '16 at 22:21