Selection Sort
Selection Sort
SELECTIO
N SORT
Why we do sorting?
INTRODUCTION
DEFINITION
KINDS OF SELECTION
SORT
ASCENDING ORDER
ALGORITHM:
i. Find smallest element (of remaining elements).
ii. Swap smallest element with current element (starting
at index 0).
iii. Finished if at the end of the array. Otherwise, repeat 1
and 2 for the next index.
ALGORITHM (cont.):
FOR i = 1 TO n - 1
min = i
FOR j = i + 1 TO n
IF x(min) > x(j) THEN
min = j
END IF
temp = x(i)
x(i) = x(min)
x(min) = temp
EXAMPLE
70 75 89 61 37
Smallest is 37
Swap with index 0
37 75 89 61 70
Smallest is 61
Swap with index 1
37 61 89 75 70
Smallest is 70
Swap with index 2
37 61 70 75 89
Smallest is 75
Swap with index 3
Swap with itself
37 61 70 75 89
Dont need to do
last element
because theres
only one left
37 61 70 75 89
DESCENDING ORDER
ALGORITHM (cont.):
FOR i = 1 TO n - 1
max = i
FOR j = i + 1 TO n
IF x(max) < x(j) THEN
max = j
END IF
temp = x(i)
x(i) = x(max)
x(max) = temp
EXAMPLE
98 84 67 1 35
Largest is 35
Swap with index 3
98 84 67 35 1
Dont need to do last
element because
theres only one left
98 84 67 35 1
Time efficiency
Comparisons: n(n-1)/2
Exchanges: n (swapping
largest into place)
Overall: (n2), best and worst
cases
SUMMARY
REFERENCE
http://www.personal.kent.edu/~rmuhamma/Al
gorithms/MyAlgorithms/Sorting/selectionSort.h
tml
http://courses.cs.vt.edu/~csonline/Algorithms/
Lessons/SelectionCardSort/selectioncardsort.ht
ml
THANK YOU!