You are on page 1of 14

Design and Analysis of

Algorithm
WEEK 4
Selection sort
 This algorithm is called selection sort because it repeatedly selects the
next-smallest element and swaps it into place.
 In computer science, selection sort is an in-place comparison sorting
algorithm.
 It has an O(n²) time complexity, which makes it inefficient on large lists,
and generally performs worse than the similar.
Continue…
 Worst complexity: n^2
 Average complexity: n^2
 Best complexity: n^2
 Space complexity: 1
 Method: Selection
 Stable: No
 Class: Comparison sort
Now sort the following according to
Selection sort:

16 54 41 1 19 21 41
Now sort the following according to
Selection sort:

73 51 4 22 91 81 36
Now sort the following according to
Selection sort:

696 588 431 944 119 21 441 976


 # Selection sort in Python
 def selectionSort(array, size):
 for step in range(size):
 min_idx = step
 for i in range(step + 1, size):
 # to sort in descending order, change > to < in this line
 # select the minimum element in each loop
 if array[i] < array[min_idx]:
 min_idx = i
 # put min at the correct position
 (array[step], array[min_idx]) = (array[min_idx], array[step])
 data = [-2, 45, 0, 11, -9]
 size = len(data)
 selectionSort(data, size)
 print('Sorted Array in Ascending Order:')
 print(data)
Now sort the following according to
Selection & Bubble sort:

94 34 27 9 75 64 58

You might also like