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

2
  • 1
    stackoverflow.com/questions/13766209/… Commented Jun 7, 2016 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];. Commented Jun 7, 2016 at 21:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.