1
Sorting AnimationChapter 10
2
Selection Sort
Another way of sorting is the selection sort
The main idea is to keep finding the smallest (and next smallest) items in the array
And move them into correct position (swap)
3
Selection Sort
45 < smallest? F
45
smallest
0
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
0
n
4
Selection Sort
32 < smallest? T
45
smallest
0
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
1
n
5
Selection Sort
32 < smallest? T
32
smallest
1
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
1
n
6
Selection Sort
56 < smallest? F
32
smallest
1
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
2
n
7
Selection Sort
9 < smallest? T
32
smallest
1
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
3
n
8
Selection Sort
9 < smallest? T
9
smallest
3
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
3
n
9
Selection Sort
21 < smallest? F
9
smallest
3
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
4
n
10
Selection Sort
77 < smallest? F
9
smallest
3
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
5
n
11
Selection Sort
17 < smallest? F
9
smallest
3
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
6
n
12
Selection Sort—SWAP!
9
smallest
3
small_pos
0
k
data
0 1 2 3 4 5 6 7
45 32 56 9 21 77 18 17
6
n
Swap(data[k], data[small_pos]);
13
Selection Sort
32 < smallest? F
32
smallest
1
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
1
n
14
Selection Sort
32 < smallest? F
32
smallest
1
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
2
n
15
Selection Sort
45 < smallest? F
32
smallest
1
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
3
n
16
Selection Sort
21 < smallest? T
32
smallest
1
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
4
n
17
Selection Sort
21 < smallest? T
21
smallest
4
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
4
n
18
Selection Sort
77 < smallest? F
21
smallest
4
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
5
n
19
Selection Sort
18 < smallest? T
21
smallest
4
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
6
n
20
Selection Sort
18 < smallest? T
18
smallest
6
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
6
n
21
Selection Sort
17 < smallest? T
18
smallest
6
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
7
n
22
Selection Sort
17 < smallest? T
17
smallest
7
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
7
n
23
Selection Sort—SWAP!
17
smallest
7
small_pos
1
k
data
0 1 2 3 4 5 6 7
9 32 56 45 21 77 18 17
7
n
Swap(data[k], data[small_pos]);
24
Selection Sort—and so on
56 < smallest? F
56
smallest
2
small_pos
2
k
data
0 1 2 3 4 5 6 7
9 17 56 45 21 77 18 32
2
n
Top Related