For i=1..n-1
Find (select) the smallest element in i..n.
Swap this element with a[i].
| Original | 34 | 8 | 64 | 51 | 32 | 21 | Swaps |
| After i=1 | 64 | 51 | 32 | 21 | 1 | ||
| After i=2 | 8 | 64 | 51 | 32 | 1 | ||
| After i=3 | 8 | 21 | 51 | 34 | 1 | ||
| After i=4 | 8 | 21 | 32 | 64 | 1 | ||
| After i=5 | 8 | 21 | 32 | 34 | 1 |
What if the input data was already sorted in ascending order?
What if the input data was already sorted in descending order?
Is the sort stable?
Selection Sort: select [134]
% gcc -o select select.c > tcc select.c
Data File with Test Case: insert.dat: 6 34 8 64 51 32 21
% select insert.dat 6 15 15 [ 8 21 32 34 51 64 ] 0 0
Selection Sort: select.dat [135]
% select insert.dat step n move comp 1 2 3 4 5 6 i j 6 0 0 [ 34 8 64 51 32 21 ] 0 0 6 0 1 [ 34 8 64 51 32 21 ] 1 2 6 0 2 [ 34 8 64 51 32 21 ] 1 3 6 0 3 [ 34 8 64 51 32 21 ] 1 4 6 0 4 [ 34 8 64 51 32 21 ] 1 5 6 0 5 [ 34 8 64 51 32 21 ] 1 6 6 3 5 [ 8 34 64 51 32 21 ] 1 7 6 3 6 [ 8 34 64 51 32 21 ] 2 3 6 3 7 [ 8 34 64 51 32 21 ] 2 4 6 3 8 [ 8 34 64 51 32 21 ] 2 5 6 3 9 [ 8 34 64 51 32 21 ] 2 6 6 6 9 [ 8 21 64 51 32 34 ] 2 7 6 6 10 [ 8 21 64 51 32 34 ] 3 4 6 6 11 [ 8 21 64 51 32 34 ] 3 5 6 6 12 [ 8 21 64 51 32 34 ] 3 6 6 9 12 [ 8 21 32 51 64 34 ] 3 7 6 9 13 [ 8 21 32 51 64 34 ] 4 5 6 9 14 [ 8 21 32 51 64 34 ] 4 6 6 12 14 [ 8 21 32 34 64 51 ] 4 7 6 12 15 [ 8 21 32 34 64 51 ] 5 6 6 15 15 [ 8 21 32 34 51 64 ] 5 7
Selection Sort: select.c [136]
void selection(input_type a[], int n) {
int i,j,min_pos;
input_type tmp;
for (i=1; i<n; i++) { /* Invariant: ? */
min_pos = i;
for (j=i+1; j<n; j++)
if (a[j] < a[min_pos]) min_pos = j;
/* what if i == min_pos */
tmp = a[i];
a[i] = a[min_pos];
a[min_pos] = tmp;
}
}
How is the inner loop structure different than insertion sort?
What is the invariant?
And how does it differ from insertion sort?
Selection Sort: Analysis [137]
How many times does the outer loop execute?
How many times does the inner loop execute?
What is the upper-bound on rate of growth? O( )
Data Compares: O( )
Data Moves: O( )
Exact Number of Data Compares:
Exact Number of Data Moves: