Selection sort builds a sorted list one element at a time: find the smallest value that is not yet in place, and swap it into the next position. It is one of the simplest sorting algorithms, which makes it a good place to start thinking about how sorts work and what they cost.
The array is split into two parts by a boundary that moves from left to right:
Each pass does the same three things:
After n − 1 passes, only one element is left in the unsorted part, and it must be the largest, so the array is sorted.
Sorting {64, 25, 12, 22, 11}, the array from the class code. Blue cells are sorted; the yellow cell is the minimum found in that pass.
This is the class code. The array in main() changes to match what you sort.
Comparisons. Pass 1 compares n − 1 pairs, pass 2 compares n − 2, and so on down to 1. That adds up to
(n − 1) + (n − 2) + … + 1 = n(n − 1) / 2
which is O(n²). The inner loop always runs to the end of the array, whatever the data looks like, so the count is exactly the same for sorted, random and reversed input. Selection sort is not adaptive: it gains nothing from data that is already in order.
Swaps. There is at most one swap per pass, so at most n − 1 swaps in total, which is O(n). Few algorithms move data this little, which helps when writing to memory is expensive.
Memory. It sorts in place, using only a few extra variables: O(1) extra space.
5 + 4 + 3 + 2 + 1 = 15, which is 6 · 5 / 2. It is 15 no matter how the values are arranged.
When only one element is left in the unsorted part, it is the largest value, and it is already in the last position. There is nothing to compare it with.
The swap can jump a value over others. In 5a, 3, 5b, 2, the first pass swaps 2 with 5a, sending 5a behind 5b: 2, 3, 5b, 5a. The two 5s have changed order.
Change the comparison to arr[j] > arr[min_idx], so each pass selects the largest remaining value. (The variable would then be better named max_idx.)