Books are notoriously flawed.
Good books are reviewed by several people who can fix those kinds of problems. But even then, some do slip through.
BTW, this is a
selection sort, not an insertion sort.
The basic idea is this: an array has n elements, indexed 0 to n-1.
0 1 2 3 4
[5] [3] [2] [1] [4] |
Sort has an index variable
i that counts through those values.
Initially
i equals 0, so we'll find the smallest value in the entire array with
findSmallest(aray,i,5)
and swap it with the item at
i:
0 1 2 3 4
[5] [3] [2] [1] [4]
↑ ↑
i smallest |
0 1 2 3 4
[1] [3] [2] [5] [4] |
Notice that at this point, every element of the array with index ≤
i is already sorted.
0 │ 1 2 3 4
[1]│[3] [2] [5] [4]
sorted │ |
Let's increment
i (so now it is equal to 1) and continue by finding the smallest value in the remainder of the array (from
i to the end) with
findSmallest(aray,i,5)
and again swap it with the item at
i:
0 1 2 3 4
[1] [3] [2] [5] [4]
↑ ↑
i smallest |
0 1 2 3 4
[1] [2] [3] [5] [4] |
Again, notice that you now have sorted (x≤
i) and unsorted (x>
i) sections:
0 1 │ 2 3 4
[1] [2]│[3] [5] [4]
sorted │ |
Again, increment
i and repeat. This time we find that
i and
findSmallest(aray,i,size)
have the same value, so we swap the element at index 2 with itself (which changes nothing). Nevertheless, we are guaranteed that the elements (x≤
i) are all properly sorted.
0 1 2 3 4
[1] [2] [3] [5] [4]
↑
i,smallest |
0 1 2 3 4
[1] [2] [3] [5] [4] |
0 1 2 │ 3 4
[1] [2] [3]│[5] [4]
sorted │ |
And again:
0 1 2 3 4
[1] [2] [3] [5] [4]
↑ ↑
i smallest |
0 1 2 3 4
[1] [2] [3] [4] [5] |
0 1 2 3 │ 4
[1] [2] [3] [4]│[5]
sorted │ |
This is where your algorithm
should stop -- as the final element will always be the largest one left. But it doesn't because
i<
size, so we'll increment
i and repeat, swapping the final element with itself:
0 1 2 3 4
[1] [2] [3] [4] [5]
↑
i,smallest |
0 1 2 3 4
[1] [2] [3] [4] [5] |
0 1 2 3 4 │
[1] [2] [3] [4] [5]│
sorted │ |
(If you want to end early, make sure
sort() makes
i from 0 to
size-1.)
You can see a nice animation at the FAQ page on selection sort:
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/selection-sort/
Hope this helps.