Selection Sort
Selection Sort
STRUCTURES
MAHESH GOYANI
MAHATMA GANDHI INSTITUE OF TECHNICAL EDUCATION & RESEARCH CENTER
mgoyani@rediffmail.com
In pseudo code:
for each element from first to last
find smallest successive element
swap the elements
20 8 5 10 7
5 8 20 10 7
5 7 20 10 8
5 7 8 10 20
5 7 8 10 20
7 0
6 0
5 0
4 0
3 0
2 0
1 0
0
[ [0]
1 ] [ [1]
2 ] [ [2]
3 ] [[3]
4 ] [ [4]
5 ] [[5]
6 ]
(C) GOYANI MAHESH 5
7 0
6 0
5 0
4 0
3 0
2 0
1 0
0
[ [0]
1 ] [ [1]
2 ] [ [2]
3 ] [[3]
4 ] [ [4]
5 ] [[5]
6 ]
(C) GOYANI MAHESH 6
Part of the array is now sorted.
4 0
3 0
2 0
1 0
0
[ [0]
1 ] [ [1]
2 ] [ [2]
3 ] [[3]
4 ] [ [4]
5 ] [[5]
6 ]
(C) GOYANI MAHESH 7
Find the smallest element in the unsorted side.
The process
continues...!!
22
13 45 13
22 97 43
13 45
22 22
45 97 43
13 22 43
45 97 45
43
13 22 43 97
45 45
97
13 22 43 45 97 DONE..!!
12
6 12
6 22 14 8 17
6 8
12 22 14 12
8 17
6 8 12
22 14 12
22 17
6 8 12 14 17
22 22
17
7 2 8 5 4
2 7 8 5 4
2 4 8 5 7
2 4 5 8 7
2 4 5 7 8
Analysis of the code shows that the outer loop executes n-1 times;
for the first iteration of the outer loop, the inner loop executes n-1
times
for the second iteration of the outer loop, the inner loop executes n-
2 times
etc
for the last iteration of the outer loop, the inner loop executes 1 time